http://qs321.pair.com?node_id=1035782


in reply to how to print out side of foreach loop($k1 $a{$k1}) ?

G'day virudinesh,

Perhaps you could clarify your intent or, at least, the rationale behind what you want. Currently, you're doing this:

$ perl -Mstrict -Mwarnings -E ' my %a=(); $a{1}{"a"}{"A"}="FIRST"; $a{1}{"c"}{"B"}="THIRD"; $a{1}{"b"}{"C"}="SECOND"; foreach my $k1 ( sort keys %a ) { foreach my $k2 ( sort keys %{$a{$k1}} ) { foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) { print "$a{$k1}{$k2}{$k3}\n"; } } } ' FIRST SECOND THIRD

Did you perhaps want something like this:

$ perl -Mstrict -Mwarnings -E ' my @items_to_print_outside_loop; my %a=(); $a{1}{"a"}{"A"}="FIRST"; $a{1}{"c"}{"B"}="THIRD"; $a{1}{"b"}{"C"}="SECOND"; foreach my $k1 ( sort keys %a ) { foreach my $k2 ( sort keys %{$a{$k1}} ) { foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) { push @items_to_print_outside_loop, "$a{$k1}{$k2}{$k3}"; } } } print join("\n", @items_to_print_outside_loop), "\n"; ' FIRST SECOND THIRD

or like this:

$ perl -Mstrict -Mwarnings -E ' sub print_outside_loop { print "@_\n" } my %a=(); $a{1}{"a"}{"A"}="FIRST"; $a{1}{"c"}{"B"}="THIRD"; $a{1}{"b"}{"C"}="SECOND"; foreach my $k1 ( sort keys %a ) { foreach my $k2 ( sort keys %{$a{$k1}} ) { foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) { print_outside_loop($a{$k1}{$k2}{$k3}); } } } ' FIRST SECOND THIRD

Update: removed -Mdiagnostics (3 instances). A cut-and-paste error which got accidentally propagated. It doesn't hurt but it's not needed and might be confusing with respect to the reason for its inclusion. (Oops! Update of update: s/It does hurt/It doesn't hurt/)

-- Ken