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.

Replies are listed 'Best First'.
Re: Re: Want a Hashref. Getting a List in Scalar Context.
by chip (Curate) on May 04, 2004 at 20:37 UTC
    All things being equal, it's good to avoid return; it's an extra opcode that does nothing when it's at the end of the function.

        -- Chip Salzenberg, Free-Floating Agent of Chaos

      All things being equal, it's good to use return; it's an extra opcode that does nothing when it's at the end of the function but it adds to the readability.
        Additional redundancy may improve readability for newbies, but that way lay the elimination of all implicit features, and then you've got Python.

        "Final expression is return value" is an easy and basic meme for Perl, going all the way back to Perl 1. The unnecessary use of return deserves, not recommendation, but quiet disdain.

            -- Chip Salzenberg, Free-Floating Agent of Chaos

      All things being equal, it's good to avoid return; it's an extra opcode that does nothing when it's at the end of the function.

      On the other hand it's executed instead of the leavesub op, so its just as efficient.

        So it does; I never noticed that before.

        I guess we're back to the "less typing good" vs. "more redundancy good" argument, already in progress.

            -- Chip Salzenberg, Free-Floating Agent of Chaos

      But doesn't "+" become an opcode too? If so, why not err on the side of maintainability?

        This form of '+' doesn't produce an opcode. Its there purely for the parser's benefit.

        map +( ... ), ...