in reply to Nested iterations throgh hash
Hi luxs,
Your problem stems from this:
The iterator used by each is attached to the hash or array, and is shared between all iteration operations applied to the same hash or array. Thus all uses of each on a single hash or array advance the same iterator location. All uses of each are also subject to having the iterator reset by any use of keys or values on the same hash or array, or by the hash (but not array) being referenced in list context. This makes each-based loops quite fragile
See https://perldoc.perl.org/functions/each.html
To demonstrate, if you use two different hashes - you'll see what I mean. Here's a revised version of your code to demonstrate
#!/usr/bin/perl use strict; use warnings FATAL => 'all'; use v5.10; # activate say feature my $h1 = {'a'=>1, 'b'=>2, 'c'=>3, 'd'=>4,}; my $h2 = {'v'=>6, 'x'=>7, 'y'=>8, 'z'=>9,}; while( my ($k1, $v1) = each(%$h1)) { say "external $k1 => $v1"; while( my ($k2, $v2) = each(%$h2)) { say "internal $k2 => $v2"; } # getchar to pause iteration after inner loop print "getchar to pause iteration after inner loop\n"; my $c = <>; }
Best of luck
Shadow
|
|---|