CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
two dimensional foreach iteration

 



huaiyanggongzi
Novice

Dec 18, 2011, 8:23 PM

Post #1 of 2 (416 views)
two dimensional foreach iteration Can't Post

There has a two dimensional iteration,

foreach my $fy (keys %$ids)

{

foreach my $ci (keys %{$ids->{$fy}}) {$set{$ci} = 1}

}

What confuses me is how to analyze the part of (keys %{$ids->{$fy}})? Moreover, can I write $set{$ci} as $set->ci?


BillKSmith
Veteran

Dec 19, 2011, 11:35 AM

Post #2 of 2 (406 views)
Re: [huaiyanggongzi] two dimensional foreach iteration [In reply to] Can't Post

From your code fragment, we can infer that
$ids is a reference to a hash of hashes and
that %set is a hash which probably is not initialized.

The loop initializes %set with all the keys of all the inner hashes.
The corresponding values are all set to 1.

Your data structure reference is hard to analyze because it uses a
mixture of brace and arrow notation. The pure brace notation which I used is exactly equivalent, but I find easier to understand. Refer to "Using References" (Method 2) in perldoc perlref. Some
of my braces are unnecessary, but method 2 always works!

Your question about %set is not valid perl. You will need $set->{$ci} if %set is declared as a reference to a hash rather than as a hash.


Code
  

use strict;
use warnings;
use Data::Dumper qw( Dumper );
my %set;
my $ids = {
fy0 => {
ci00 => 'value00',
ci01 => 'value01',
ci02 => 'value02',
ci03 => 'value03',
ci04 => 'value04',
},
fy1 => {
ci10 => 'value10',
ci11 => 'value11',
ci12 => 'value12',
ci13 => 'value13',
ci14 => 'value14',
},
fy2 => {
ci20 => 'value20',
ci21 => 'value21',
ci22 => 'value22',
ci23 => 'value23',
ci24 => 'value24',
},
};
foreach my $fy ( keys %$ids ) {

# foreach my $ci ( keys %{ $ids->{$fy} } ) {
foreach my $ci ( keys %{ ${$ids}{$fy} } ) {
$set{$ci} = 1;
}
}

print Dumper \%set;

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives