http://qs321.pair.com?node_id=274781


in reply to $_ scoping issues

When you do foreach (list_of_stuff), $_ is aliased to each entry in the list in turn. Hence, $_ *is* $u->{loc} and has the same address.

If you want to copy each list element into another variable for processing (which is generally the wise thing to do) the usual solution would be foreach my $foo (list_of_stuff).

On an unrelated issue, I betcha that foreach ($u->{loc}) is a bug. $u->{loc} is, and always will be, a scalar, so there's no point in the foreach.

Replies are listed 'Best First'.
Re: Re: $_ scoping issues
by swkronenfeld (Hermit) on Jul 18, 2003 at 22:19 UTC
    DrHyde,

    > When you do foreach (list_of_stuff), $_ is aliased to each entry in the list in turn. Hence, $_ *is* $u->{loc} and has the same address.

    This is exactly my mistake! I believed that each element was copied from the list_of_stuff into $_ one at a time. Good to know.

    > I betcha that foreach ($u->{loc}) is a bug

    You are write that it's a scalar, and I know it looks like I forgot to do something like @{($u->{loc})}, but it's actually my intended affect. Maybe I'm on the wrong track with this, so I'll post it in case people might have some useful suggestions for me.

    I'm using the foreach to do an implicit assignment into $_, and then pattern match on $_. In addition, the foreach loop has the added bonus of allowing flow control (without creating a block)

    foreach ($u->{loc}) { if(/n/) { print "option n" } elsif(/m/) { print "option m" } elsif(/w/) { print "option w" } ... }

    I'm not sure why I originally did it this way (maybe I read something in one of the O'Reilly books that used this technique?), so I adapted it. Is there a better way? If I don't need the flow control advantage, is it better to simply assign $_ = $u->{loc} prior to my conditional statements?