Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^5: Syntax for casting map to a hash or an array

by stevieb (Canon)
on Apr 05, 2017 at 18:24 UTC ( #1187173=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1187173]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2020-08-07 12:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (44 votes). Check out past polls.

    Notices?