Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Hash Values into Array

by Laurent_R (Parson)
on Aug 16, 2013 at 21:35 UTC ( #1049799=note: print w/ replies, xml ) Need Help??


in reply to Hash Values into Array

Another solution, perhaps somewhat simpler, might be to use the values function, rather than the keys function. Something like this:

for my $os (values %$info) { for my $testcase (values %$os) { push @errors, values %$testcase } }

This should also work if you have several errors possible for one testcase, such as 'error1', 'error2', etc.

Update: corrected the typos indicated by kcott.


Comment on Re: Hash Values into Array
Download Code
Re^2: Hash Values into Array
by sundialsvc4 (Monsignor) on Aug 17, 2013 at 01:03 UTC

    ... an excellent observation.   ++ ...

Re^2: Hash Values into Array
by kcott (Abbot) on Aug 17, 2013 at 06:39 UTC
    "for $my os (values %info) {"

    Two corrections:

    • Typo: $my os should be my $os
    • Datatype: %info should be %$info (to match OP's $info->{$os}...)

     

    "This should also work if you have several errors possible for one testcase, such as 'error1', 'error2', etc."

    You're manufacturing data that the OP hasn't specified or even hinted at. I don't think this is a good idea. Furthermore, you're not targeting the specific key (i.e. error) that the OP did specify; you are, in fact, targeting every key that exists. Consider this scenario (using your code, with the corrections shown above):

    $ perl -Mstrict -Mwarnings -le ' my $info = { win => { t1 => { error => "missing arg" }, t2 => { skipped => "no network" } }, nix => { t1 => { error => "wrong type" }, t2 => { success => 1 } } }; my @errors; for my $os (values %$info) { for my $testcase (values %$os) { push @errors, values %$testcase } } print for @errors; ' no network missing arg wrong type 1

    -- Ken

      You're manufacturing data that the OP hasn't specified or even hinted at. I don't think this is a good idea. Furthermore, you're not targeting the specific key (i.e. error) that the OP did specify; you are, in fact, targeting every key that exists.

      You're right, Ken, but the OP did not provide any data, so I made some assumptions about the contents of the data structure. I quickly populated a nested data structure and tested the solution under the Perl debugger. The idea was only to show that using the values function rather than the keys function saved some typing and made the solution somewhat simpler.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2014-08-29 01:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (275 votes), past polls