Anti-nuisance lawsuit warning: The purpose of these notes is to remind me, Zoegond, of stuff or to help me work stuff out. They may contain mistakes.

Quick

  • ($a, $b....) = unpack("A2A7...", $packed)
  • push( array, list )

Saturday, March 2, 2013

Perl hash slices

Well blow me tight. Not only can you do hash slices in Perl, but that functionality's been there since Perl 4 at least.

I suppose my understanding of Perl must have been built in such a logical way that it ran a hundred years to the day...

So just as you might have this:

 
@a = (1,2,3); 
print @a[1,2];
and get '23', then you might have this:
%a = qw(alpha 1 beta 2 gaga 3); 
print @a{ qw(beta gaga) };
and also get '23'.

NB that it is an @ and not a % as the first character there.

To slice a hash reference just replace @a above with @$r or @{$r} .

(New) You can also slice in a sort of 'select column' way, where your result is a subset of the hash's keys and values rather than just values:

%a = qw(alpha 1 beta 2 gaga 3); 
%b = %a{ qw(beta gaga) };
and end up with %b being (beta => 2, gaga => 3);

To do that with a reference, replace %a above with %$r or %{$r} .

This works in Perl 5.24 but not in 5.8.2 .

Followers

Blog Archive