Addendum to Perl Antipattern #3.14159

ziggy on 2002-03-13T03:06:42

I forgot to mention hashref initializers in that previous post. They're not much different. Instead of:

## Stock assignment
my %hash = %defaults;

## Restricted assignment
my %hash; @hash{@keys} = @defaults{@keys};
We get this:
## We want a *copy* of the original hash, not a reference to it
my $hashref = {%defaults};

## We want a *reference* to the original hash,not a copy of it (atypical case)
my $hashref = \%defaults;

## Now we've got to use map or foreach to get restricted assignment...
my $hashref = {};
$hashref->{$_} = $defaults{$_} foreach (@keys);
The foreach is better than the alternative -- an explicit foreach loop or worse - a map within a hashref constructor. Keep in mind that the common case -- initializing a hashref to a set of defaults -- is a well-supported operation.


You forgot:

pudge on 2002-03-13T19:30:17

my $hashref = {};
@{$hashref}{@keys} = @defaults{@keys};

Re:You forgot:

ziggy on 2002-03-13T20:08:31

thanks. I didn't balance get the parens balanced properly when I was playing with it. :-)

Re:You forgot:

koschei on 2002-03-14T13:33:22

Aw crap. I hadn't gotten to this comment before I posted my comment to the previous journal entry. Shucks.