Tuesday, February 12, 2008

A Perl of Wisdom for Me

Every so often I find a really nice construct I didn't know existed in Perl and I can never remember it. Well I'm going to post them here and see if it kicks my memory into gear.

Copying an array

my $array = [1,2,3]; # From somewhere
my $copy = [@{$array}]; #De-reference array into an anonymous array & assign

Populating a hash from an array via a slice

my %hash;
my @keys = qw/ key key2 key3 /;
@hash{@keys} = (); #Populate hash with keys and no values

#Populate hash with keys from array and values from same position in the assigned list
@hash{@keys} = (1,2,3);

Copying one hash to another

my $input = {key => 1, key2 => 2, key3 => 3};
my %target = (key, 4);
#And now for the copy magic
@target{keys(%{$input})} = values(%{$input}); #1 deref is better than 2 but is ok for tiny calls

Anyway I hope this is of use to someone other than me. If not then it'll be of some use to me.