[Pdx-pm] for vs foreach question

Ovid curtis_ovid_poe at yahoo.com
Wed Dec 10 12:53:01 CST 2003


Thomas,

As Jeff pointed out, your foreach loop is not doing the same thing as
the for loop.  When you do this:

  my @in_list = qw( big bad snuffleupagus );
  foreach my $foo (@in_list) {

$foo is getting set to each item in @in_list, not the indices.  In
other words, the second time through the loop, $foo will be set to
'bad', not to '1'.

Cheers,
Ovid

--- Thomas Keller <kellert at ohsu.edu> wrote:
> Hi all,
> I thought the "foreach" keyword was a synonym for the "for" keyword.
> So 
> I'm perplexed why the following loops don't give the same output:
> ############# code snippet ############
> my $aref = [ ['Tom', 'Pattie', 'Dave', 'Dan', 'John'],
> 				['Lee', 'Mike', 'Anita','Kathryn', 'Cecelia'],
> 				['Cybele','Tomas','BenJoaquin','Anna'],
> 				['Nick','Sam','Kate'],['Kim','Mike'],
> 				['Brian','Marissa'],
> 				['null'] ];
> 
> #print 2-D array - this works fine
> for (my $i = 0; $i < scalar @$aref; ++$i) {
> 	for (my $j = 0; $j < scalar @{$aref->[$i]}; ++$j) {
> 		print $aref->[$i][$j], " ";
> 	}
> 	print "\n";
> }
> 
> #print 2-D array - ?? - doesn't work
> foreach my $i (@$aref) {
> 	foreach my $j (@{$aref->[$i]}) {
> 		print $aref->[$i][$j], " ";
> 	}
> 	print "\n";
> }
> 
> ###########
> Thanks for any help understanding this.
> Tom K.
> 
> _______________________________________________
> Pdx-pm-list mailing list
> Pdx-pm-list at mail.pm.org
> http://mail.pm.org/mailman/listinfo/pdx-pm-list


=====
Silence is Evil            http://users.easystreet.com/ovid/philosophy/indexdecency.htm
Ovid                       http://www.perlmonks.org/index.pl?node_id=17000
Web Programming with Perl  http://users.easystreet.com/ovid/cgi_course/



More information about the Pdx-pm-list mailing list