Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^2: Nested iterations throgh hash

by luxs (Beadle)
on Feb 11, 2020 at 20:47 UTC ( [id://11112812]=note: print w/replies, xml ) Need Help??


in reply to Re: Nested iterations throgh hash
in thread Nested iterations throgh hash

Yes! This is a solution to my problem

I've checked a few nested "for my $k (keys %$h) {}" loops and they work perfectly. This means that "each" mechanism is not very good to use.

What is the real task? I have external data supplies as a hash reference, and I do have this hash reference available through all my code, fetching data as required.

Replies are listed 'Best First'.
Re^3: Nested iterations throgh hash
by haukex (Archbishop) on Feb 11, 2020 at 21:01 UTC
    This means that "each" mechanism is not very good to use.

    It depends: As described in each, every hash has an iterator that is per-hash. The code you showed in the root node doesn't work because both of the each calls access the same iterator. My solution fetches the list of keys once at the beginning of the for loop, which will use a bit more memory; I could have done this for both loops, but in this example I knew that the inner each would work because there's nothing else interfering with the iterator, so I kept it. keys does have the advantage that if you want to loop through the hash in a predictable order, you can just say sort keys %hash.

    Also, note that if you want to create the Cartesian product of two sets of hash keys, there are plenty of modules that will do this, see the links in the section "See Also" in my module Algorithm::Odometer::Tiny.

    use warnings; use strict; use Algorithm::Odometer::Tiny; my $h = {a=>1, b=>2, c=>3, d=>4}; my $odo = Algorithm::Odometer::Tiny ->new( [sort keys %$h], [sort keys %$h] ); while ( my @x = $odo->() ) { print "outer: $x[0], inner: $x[1]\n"; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-03-29 13:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found