* Adriano Ferreira <a.r.ferreira gmail.com> [2007-08-30
17:25]:
> On 8/30/07, via RT Worik <perlbug-followup perl.org> wrote:
> > # New Ticket Created by Worik
> > # Please include the string: [perl #45041]
> > # in the subject line of all future correspondence
about this issue.
> > # <URL: h
ttp://rt.perl.org/rt3/Ticket/Display.html?id=45041 >
> >
> >
> > This is a bug report for perl from
worik.stanton gmail.com,
> > generated with the help of perlbug 1.35 running
under perl v5.8.8.
> >
> >
> >
------------------------------------------------------------
-----
> > [Please enter your report here]
> > This little programme demonstrates the problem
> >
> > my test = (1..12);
> > print join(", ", test)."n";
> > foreach my $t( test){
> > if($t % 2 ){
> > $t *= -1;
> > }
> > }
> > print join(", ", test)."n";
>
> As Michael Schwern said, this turns out to be the way
the
> for/foreach loop is documented to work. Using aliasing,
makes
> it more efficient (but dangerous for the unaware as you
have
> discovered for your self).
It’s not just a matter of efficiency, it’s also a
feature. F.ex.
you can say something like
foreach my $owner ( values %owner_of ) {
$owner =~ s/Tom/Dick/;
# ...
}
and it will actually modify the values in the hash.
> To loop through an array, without worrying about
changing the
> contents of the array elements, you may use an idiom
like that
>
> foreach ( test){
> my $t = $_; # makes a copy
> if($t % 2 ){
> $t *= -1;
> }
> }
Or even simpler:
foreach ( my copy = test ) {
# ...
}
Regards,
--
Aristotle Pagaltzis // <http://plasmasturm.org/&g
t;
|