Loop consuming my list

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View


I was surprised to see in my own code, a difference between
the two lines (out of context...):

    $self->rmhlink($type, $_) for @pl;
    for my $p (@pl) { $self->rmhlink($type, $p) }

The former consumed the contents of @pl.
The latter did not.

The rmhlink (member) function reads its arguments from @_,
and returns a value, often undef.

I tried to reproduce the case naively, but failed:

$ perl -wle '@s=qw(a b c);sub f;f($_)for@s;map{print $_}@s'

Is there thus an interaction from the package?

I cannot get this either...

$ perl -wle 'package Foo;@s=qw(a b c);sub new;bless $s,
$t}sub foo;$f=new Foo;$f->foo($_)for@s;map{print $_}@s'

I am afraid this is a symptom that I missed something fundamental...
Who is eating my list?


Re: Loop consuming my list

Quoted text here. Click to load it

You probably have to defined what you mean by 'consumed the contents
of @pl'. I assume that you mean that the content of @pl has changed
somehow. The problme is that the first construction makes $_ an alias
to the elements in @pl and that $_ is a global variable.

In perl 5.10 you can make $_ a lexical variable by adding a 'my $_;'
somewhere in scope befor the loop:

  my $_;
  $self->rmhlink($type, $_) for @pl;

For older perls you have to localize $_ in your rmhlink method. I
would probably do both.

See also:
http://peter.makholm.net/2009/06/24/the-evil-of-a-global-_ /


Re: Loop consuming my list

Thank you Peter,

Quoted text here. Click to load it

Indeed. In this case, the list was empty after running the loop.

Quoted text here. Click to load it

That's what I didn't understand.
I thought it was lexical...

Quoted text here. Click to load it

Thanks. I can now see that it is what I did, without the
side-effect of the name.

Quoted text here. Click to load it

I *did* miss something important.


Re: Loop consuming my list

Marc Girod wrote:
Quoted text here. Click to load it

It is not possible to change array size by manipulating $_.
The array size must be the same.

Dipl.-Inform. Frank Seitz
Anwendungen für Ihr Internet und Intranet
Tel: 04103/180301; Fax: -02; Industriestr. 31, 22880 Wedel

Homepage:    http://www.fseitz.de /
XING-Profil: http://www.xing.com/profile/Frank_Seitz2

Re: Loop consuming my list

Quoted text here. Click to load it

Sorry, you are correct. The items were set to ''.
I tried the advice on 5.8.8, and checked that I cannot
make $_ lexical there, but that local $_ within rmhlink

I believe that I'll be happy with the insight, and with
lexicalizing by naming as I did.


Site Timeline