>From the Camel Book, chapter 2, section 6:
"2.6.4.3 Foreach loops
[...]
The foreach keyword is actually a synonym for the for keyword, so you can use
foreach for readability or for for brevity. If VAR is omitted, $_ is used. If
LIST is an actual array (as opposed to an expression returning a list value),
you can modify each element of the array by modifying VAR inside the loop.
That's because the foreach loop index variable is an implicit alias for each
item in the list that you're looping over.
[...]
Note that there is no way with foreach to tell where you are in a list. You can
compare adjacent elements by remembering the previous one in a variable, but
sometimes you just have to break down and write an ordinary for loop with
subscripts. That's what for is there for, after all."
-dZ.
----- Original Message -----
From: Brian Raven
Sent: 4/7/2006 8:54:47 AM
To: [email protected]
Subject: RE: foreach question
> Conrad, Bill (ThomasTech) <> wrote:
> > I thought that Perl had another internal variable that contained
> the
> > numerical index of each array entry without having to count them. I
> > guess what I thought was happening internally was that Perl was
> > maintaining an index of @List and returning @List[index] when in fact
> > Perl is internally making a copy of @List and popping each entry off
> > the copied list.
>
> You couldn't have been more wrong, Bill. The foreach style loop iterates
> over the provided list with the control variable ($_ unless specified)
> being an alias for each value in that list. It is not unknown for
> novices and experienced programmers alike to miss that and get
> unexpected results.
>
> Also, many people don't realise that for and foreach are synonyms. For
> example:
>
> use strict;
> use warnings;
>
> my @array = qw{a b c d e};
>
> for (@array) {
> $_ = uc $_;
> }
>
> foreach (my $i = 0; $i < @array; ++$i) {
> print "entry $i: $array[$i]\n";
> }
>
> Although I wouldn't recommend writing such counter-intuitive code for
> real.
>
> HTH, HAND
>
> --
> Brian Raven
>
>
> ______________________________________________________________________
> This email has been scanned by the MessageLabs Email Security System.
> For more information please visit http://www.messagelabs.com/email
> ______________________________________________________________________
>
> _______________________________________________
> ActivePerl mailing list
> [email protected]
> To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs