http://www.perlmonks.org?node_id=1187173


in reply to Re^4: Syntax for casting map to a hash or an array
in thread Syntax for casting map to a hash or an array

Yep, both of those work, however not for the same reason.

Dumper takes a reference of any type.

This:

{map { $_ => 'fish' } qw(one two red blue)}

... takes whatever is compiled by map, then with the outer braces, converts that into a hash reference, then returns the hash ref (same for the next one with an array). Putting the sigil in front of that block, and it will deref the created reference into a hash, and return it as a hash as opposed to a reference. For Dumper, you'd then need to dereference it before sending it in as a parameter.

Replies are listed 'Best First'.
Re^6: Syntax for casting map to a hash or an array
by cbeckley (Curate) on Apr 05, 2017 at 18:50 UTC

    Wait, what part works, but for not the same reason?

    These two work for exactly the same reason.

    say Dumper({map { $_ => 'fish' } qw(one two red blue)}); say Dumper([map { $_ => 'fish' } qw(one two red blue)]);

    These two work but NOT for the same reason, because there's an extra layer of ref->hash->ref going on?
    That's the difference you're talking about, right?

    say Dumper(\@{ {map { $_ => 'fish' } qw(one two red blue)} } ); say Dumper({map { $_ => 'fish' } qw(one two red blue)});

    Thanks,
    cbeckley

      The first two work. In the upper, an anoymous hash is constructed with map's output, in the lower, an anonymous array. In each case, Dumper just get's passed the reference and dereferences it.

      These two work but NOT for the same reason, because there's an extra layer of ref->hash->ref going on?
      say Dumper(\@{ {map { $_ => 'fish' } qw(one two red blue)} } );

      This one doesn't work, because the code is trying to dereference the anonymous hash as an array (@{ }).

      The next one is just like the upper one from the former code block.

      perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

        Ugh, right, that was a typo. I was trying to compare these two lines.

        say Dumper(\%{ {map { $_ => 'fish' } qw(one two red blue)} } ); say Dumper({map { $_ => 'fish' } qw(one two red blue)});

        Thank you for the correction.

        Thanks,
        cbeckley