Tumblelog by Soup.io
Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

October 07 2008

leobm

Things you should know about perl hashes

use Data::Dump 'pp';
# merge hash refs
my $a = {a=>1, b=>2};
my $x = {a=>4, s=>1};
my $v = {%{$a}, %{$x}};
print pp($v);
# output: { a => 4, b => 2, "s" => 1 }

# or by hash slice
my %a = (one => 1, two => 2, three => 3);
my %b = (two => 2, four => 4, six => 6);
@a{keys %b} = values %b;
print pp(\%a);

#------------------------
# further hash slices examples 

my %hash = ( a => "Alex", b => "Ben", c => "Charlie");
my ($a, $c) = @hash{qw/a c/};
print "$a, $c \n";
# output: Alex, Charlie 

#------------------------
my %hash = ();
@hash{ qw/a c/ } = qw/Alex Charlie/;
print pp(\%hash);
# output: { a => "Alex", c => "Charlie" }

#------------------------
# create unique array

my %hash = ();
my @words = qw/Alex Ben Ben Alex Charly/;
@hash{@words} =  @words;
print pp(keys %hash);
# output: ("Ben", "Alex", "Charly")

#------------------------
# set default values
use Data::Dump 'pp';
my @stuff = qw/a b c d/;
my %hashit;
@hashit{@stuff} = (1) x @stuff;
print pp(\%hashit);
#output: { a => 1, b => 1, c => 1, d => 1 }

# or multiply...
use Data::Dump 'pp';
my @stuff = qw/a b c d/;
my %hashit;
@hashit{@stuff} = (1,3,5) x @stuff;

print pp(\%hashit);
#output: { a => 1, b => 3, c => 5, d => 1 }