develooper Front page | perl.perl5.porters | Postings from November 1999

Re: [ID 19991126.002] overwriting with scalar $_ using foreach over array and inner wh ile loop [PATCH]

M.J.T. Guy
November 26, 1999 08:22
Re: [ID 19991126.002] overwriting with scalar $_ using foreach over array and inner wh ile loop [PATCH]
Message ID:
Martyn Pearce <> wrote
> Hence the while loop assigns to $_ which is an alias into @array.  No
> surprise.

But you haven't pointed out the key issue, that while never localises
any variable, unlike foreach.    And this point isn't stressed in
the current (5.005_03) documentation.

The development version (5.005_62) makes this more explicit:

Ordinarily you must assign the returned value to a variable, but
there is one situation where an automatic assignment happens.  If
and only if the input symbol is the only thing inside the conditional
of a C<while> statement (even if disguised as a C<for(;;)> loop),
the value is automatically assigned to the global variable $_,
destroying whatever was there previously.  (This may seem like an
odd thing to you, but you'll use the construct in almost every Perl
script you write.)  The $_ variables is not implicitly localized.
You'll have to put a C<local $_;> before the loop if you want that
to happen.

I think the attached patch to perlsyn would also be useful.

Mike Guy

--- ./pod/perlsyn.pod.orig	Fri Sep 17 21:23:08 1999
+++ ./pod/perlsyn.pod	Fri Nov 26 16:02:15 1999
@@ -163,6 +163,8 @@
 refers to the innermost enclosing loop.  This may include dynamically
 looking back your call-stack at run time to find the LABEL.  Such
 desperate behavior triggers a warning if you use the B<-w> flag.
+Unlike a C<foreach> statement, a C<while> statement never implicitly
+localises any variables.
 If there is a C<continue> BLOCK, it is always executed just before the
 conditional is about to be evaluated again, just like the third part of a

End of patch Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About