in reply to Want a Hashref. Getting a List in Scalar Context.
If you add a return to your set_params it works correctly. For example:
{ my @FIELDS = qw( foo bar baz); sub set_params { return { map { $_ => $_ } @FIELDS }; } } my $params = set_params; use Data::Dumper "Dumper"; print Dumper($params); __OUTPUT__ $VAR1 = { 'bar' => 'bar', 'baz' => 'baz', 'foo' => 'foo' };
Update: chip's suggestion would work as well, but I personally think using return conveys the meaning more clearly.
Update II: Using -MO=Deparse helped me to clarify what each method did.
sub set_params { { map { $_ => $_ } @FIELDS }; } $ perl -MO=Deparse /tmp/hash.pl sub set_params { { map {$_, $_;} @FIELDS; } } sub set_params { +{ map { $_ => $_ } @FIELDS }; } $ perl -MO=Deparse /tmp/hash.pl sub set_params { {map({$_, $_;} @FIELDS)}; } sub set_params { return { map { $_ => $_ } @FIELDS }; } $ perl -MO=Deparse /tmp/hash.pl sub set_params { return {map({$_, $_;} @FIELDS)}; }
I really like being able to find out exactly how Perl is trying to interpret what I wrote.
|
|---|