Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Fetch array of values from hashref

by k-mx (Acolyte)
on Sep 11, 2019 at 07:30 UTC ( #11106002=note: print w/replies, xml ) Need Help??


in reply to Fetch array of values from hashref

I think that code must be expressive, so it's nice when you use slices this way:
my $h = { foo => 1, bar => 2 }; @{ $h }{qw/ foo bar /} = ( 667, 889 ); # or postfix form: # $h->@{qw/ foo bar /} = ( 667, 889 );
But for your problem, more clear solution would be:
my @ar = values %$h; # or postfix form: # my @ar = values $h->%*;
You can read more about slices here:
perldoc perldata perldoc perlref

Replies are listed 'Best First'.
Re^2: Fetch array of values from hashref
by haukex (Chancellor) on Sep 11, 2019 at 07:39 UTC
    But for your problem, more clear solution would be:
    my @ar = values %$h;

    However, note this form is not equivalent: the order of the returned values will be random.

Re^2: Fetch array of values from hashref (updated)
by AnomalousMonk (Bishop) on Sep 11, 2019 at 15:36 UTC
    ... for your problem ...

    I would go a bit further than haukex and say that the problem exemplified in the OP is to extract the values of a subset | an ordered subset of hash keys, whereas  values %$h gives you the values of all keys (in random order!). Again, not an equivalent solution.

    Update: As a side note, WRT hash key/value ordering it's worth mentioning that keys, values, and each all state that:

    So long as a given hash is unmodified you may rely on keys, values and each to repeatedly return the same order as each other. See Algorithmic Complexity Attacks in perlsec for details on why hash order is randomized.
    The actual random ordering will differ from one run of a script to another if this security feature is enabled. (IIRC, this feature, enabled by default, can be disabled during the build of a Perl interpreter.)


    Give a man a fish:  <%-{-{-{-<

      Yes, my bad. I thought he needed all values.

      P.S. I want to share another cool hack, maybe somebody don't know about it:

      ( \$Param{Foo}, \$Param{Bar} ); \( $Param{Foo}, $Param{Bar} ); \@Param{'Foo', 'Bar'};
      You can use it in situations like this

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2019-10-15 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?