develooper Front page | perl.beginners | Postings from June 2011

Re: Using $variable outside a foreach loop

Thread Previous | Thread Next
From:
Brian Fraser
Date:
June 3, 2011 12:03
Subject:
Re: Using $variable outside a foreach loop
Message ID:
BANLkTimoLUsLYG_Ak=8ZF81qZHkhLSe9OA@mail.gmail.com
On Fri, Jun 3, 2011 at 1:23 PM, Jim Gibson <jimsgibson@gmail.com> wrote:

> Declare the variable just before the loop, and remove the 'my' from the
> foreach statement:
>
> my $name;
> foreach $name ( ... ) {
>  ...
> }
>

That won't do. What that code actually translated to is
my $name;
for my $name ( ... ) { ... }

With the second $name masking the first! IIRC this is explained somewhere in
PBP, but I don't have the book at hand right now. In any case, if you want
to use the variable outside of the for, don't name the two variables the
same.
The rough rule of thumb is that leaving off the my in a for(each) is
probably introducing subtle bugs into your program.

Brian.


Thread Previous | 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