develooper Front page | perl.beginners | Postings from March 2002

some questions about for, foreach

Thread Next
From:
Jon Molin
Date:
March 1, 2002 02:32
Subject:
some questions about for, foreach
Message ID:
3C7F5812.6825C054@resfeber.se
Hi list!

I've always thought there's a difference between for and foreach, that
for uses copies and foreach not. But there's no diff is there?

my @a = (1, 2, 3 , 4 , 5);
$_ += 2 for  (@a);
print "@a\n";
3 4 5 6 7

my @a = (1, 2, 3 , 4 , 5);
$_ += 2 foreach  (@a);
print "@a\n";
3 4 5 6 7

why isn't it possible to write:
$b += 2 for my $b (@a);
but possible to write
for my $b (@a) {$b += 2};

case 2

my @a = (1, 2, 3 , 4 , 5);
for (my $i = 0; $i <= $#a;$i++)
{
    print $a[$i], ' ';
}
print "\n";
1 2 3 4 5 

my @a = (1, 2, 3 , 4 , 5);
foreach (my $i = 0; $i <= $#a;$i++)
{
    print $a[$i], ' ';
}
print "\n";
1 2 3 4 5 


so, is foreach only an alias for for or is there some diff?

/Jon

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About