List Info

Thread: Re: Looping "foreach my $thing(@things)" places a reference not a scalar into $thing




Re: Looping "foreach my $thing(@things)" places a reference not a scalar into $thing
user name
2007-09-06 15:52:19
* Adriano Ferreira <a.r.ferreiragmail.com> [2007-08-30
17:25]:
> On 8/30/07, via RT Worik <perlbug-followupperl.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.stantongmail.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;

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )