Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

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

by kcott (Bishop)
on May 29, 2013 at 06:05 UTC ( #1035782=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2020-12-03 00:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (48 votes). Check out past polls.

    Notices?