This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re: for() and map() peculiarity
[perl5.git] / pod / perlsyn.pod
index 9caae6a..5274d28 100644 (file)
@@ -32,20 +32,23 @@ that.
 A declaration can be put anywhere a statement can, but has no effect on
 the execution of the primary sequence of statements--declarations all
 take effect at compile time.  Typically all the declarations are put at
-the beginning or the end of the script.  However, if you're using 
+the beginning or the end of the script.  However, if you're using
 lexically-scoped private variables created with my(), you'll have to make sure
 your format or subroutine definition is within the same block scope
 as the my if you expect to be able to access those private variables.
 
 Declaring a subroutine allows a subroutine name to be used as if it were a
 list operator from that point forward in the program.  You can declare a
-subroutine without defining it by just saying:
+subroutine without defining it by saying C<sub name>, thus:
 
     sub myname;
     $me = myname $0            or die "can't get myname";
 
-Though note that it functions as a list operator, not as a unary
-operator, so be sure to use C<or> instead of C<||> in this case.
+Note that it functions as a list operator, not as a unary operator; so
+be careful to use C<or> instead of C<||> in this case.  However, if
+you were to declare the subroutine as C<sub myname ($)>, then
+C<myname> would functonion as a unary operator, so either C<or> or
+C<||> would work.
 
 Subroutines declarations can also be loaded up with the C<require> statement
 or both loaded and imported into your namespace with a C<use> statement.
@@ -65,7 +68,7 @@ semicolon, unless it is the final statement in a block, in which case
 the semicolon is optional.  (A semicolon is still encouraged there if the
 block takes up more than one line, because you may eventually add another line.)
 Note that there are some operators like C<eval {}> and C<do {}> that look
-like compound statements, but aren't (they're just TERMs in an expression), 
+like compound statements, but aren't (they're just TERMs in an expression),
 and thus need an explicit termination if used as the last item in a statement.
 
 Any simple statement may optionally be followed by a I<SINGLE> modifier,
@@ -178,25 +181,26 @@ want to skip ahead and get the next record.
 
     while (<>) {
        chomp;
-       if (s/\\$//) { 
-           $_ .= <>; 
+       if (s/\\$//) {
+           $_ .= <>;
            redo unless eof();
        }
        # now process $_
-    } 
+    }
 
 which is Perl short-hand for the more explicitly written version:
 
-    LINE: while ($line = <ARGV>) {
+    LINE: while (defined($line = <ARGV>)) {
        chomp($line);
-       if ($line =~ s/\\$//) { 
-           $line .= <ARGV>; 
+       if ($line =~ s/\\$//) {
+           $line .= <ARGV>;
            redo LINE unless eof(); # not eof(ARGV)!
        }
        # now process $line
-    } 
+    }
 
-Or here's a simpleminded Pascal comment stripper (warning: assumes no { or } in strings).
+Or here's a simpleminded Pascal comment stripper (warning: assumes no
+{ or } in strings).
 
     LINE: while (<STDIN>) {
        while (s|({.*}.*){.*}|$1 |) {}
@@ -246,15 +250,15 @@ for variables declared with C<my> in the initialization expression.)
 
 Besides the normal array index looping, C<for> can lend itself
 to many other interesting applications.  Here's one that avoids the
-problem you get into if you explicitly test for end-of-file on 
-an interactive file descriptor causing your program to appear to 
+problem you get into if you explicitly test for end-of-file on
+an interactive file descriptor causing your program to appear to
 hang.
 
     $on_a_tty = -t STDIN && -t STDOUT;
     sub prompt { print "yes? " if $on_a_tty }
     for ( prompt(); <STDIN>; prompt() ) {
        # do something
-    } 
+    }
 
 =head2 Foreach Loops
 
@@ -266,15 +270,22 @@ implicitly local to the loop and regains its former value upon exiting
 the loop.  If the variable was previously declared with C<my>, it uses
 that variable instead of the global one, but it's still localized to
 the loop.  (Note that a lexically scoped variable can cause problems
-with you have subroutine or format declarations.)
+if you have subroutine or format declarations within the loop which
+refer to it.)
 
 The C<foreach> keyword is actually a synonym for the C<for> keyword, so
 you can use C<foreach> for readability or C<for> for brevity.  If VAR is
-omitted, $_ is set to each value.  If LIST is an actual array (as opposed
-to an expression returning a list value), you can modify each element of
-the array by modifying VAR inside the loop.  That's because the C<foreach>
-loop index variable is an implicit alias for each item in the list that
-you're looping over.
+omitted, $_ is set to each value.  If any element of LIST is an lvalue,
+you can modify it by modifying VAR inside the loop.  That's because
+the C<foreach> loop index variable is an implicit alias for each item
+in the list that you're looping over.
+
+If any part of LIST is an array, C<foreach> will get very confused if
+you add or remove elements within the loop body, for example with
+C<splice>.   So don't do that.
+
+C<foreach> probably won't do what you expect if VAR is a tied or other
+special variable.   Don't do that either.
 
 Examples:
 
@@ -309,12 +320,12 @@ Here's how a C programmer might code up a particular algorithm in Perl:
 Whereas here's how a Perl programmer more comfortable with the idiom might
 do it:
 
-    OUTER: foreach my $wid (@ary1) { 
+    OUTER: foreach my $wid (@ary1) {
     INNER:   foreach my $jet (@ary2) {
                next OUTER if $wid > $jet;
                $wid += $jet;
-            } 
-         } 
+            }
+         }
 
 See how much easier this is?  It's cleaner, safer, and faster.  It's
 cleaner because it's less noisy.  It's safer because if code gets added
@@ -370,19 +381,19 @@ or
 or formatted so it stands out more as a "proper" switch statement:
 
     SWITCH: {
-       /^abc/      && do { 
-                           $abc = 1; 
-                           last SWITCH; 
+       /^abc/      && do {
+                           $abc = 1;
+                           last SWITCH;
                       };
 
-       /^def/      && do { 
-                           $def = 1; 
-                           last SWITCH; 
+       /^def/      && do {
+                           $def = 1;
+                           last SWITCH;
                       };
 
-       /^xyz/      && do { 
-                           $xyz = 1; 
-                           last SWITCH; 
+       /^xyz/      && do {
+                           $xyz = 1;
+                           last SWITCH;
                        };
        $nothing = 1;
     }
@@ -416,14 +427,14 @@ a temporary assignment to $_ for convenient matching:
                /Anywhere/          && do { push @flags, '-h'; last; };
                /In Rulings/        && do {                    last; };
                die "unknown value for form variable where: `$where'";
-           } 
+           }
 
 Another interesting approach to a switch statement is arrange
 for a C<do> block to return the proper value:
 
     $amode = do {
-       if     ($flag & O_RDONLY) { "r" } 
-       elsif  ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" } 
+       if     ($flag & O_RDONLY) { "r" }
+       elsif  ($flag & O_WRONLY) { ($flag & O_APPEND) ? "a" : "w" }
        elsif  ($flag & O_RDWR)   {
            if ($flag & O_CREAT)  { "w+" }
            else                  { ($flag & O_APPEND) ? "a+" : "r+" }
@@ -475,14 +486,14 @@ encounters a line that begins with an equal sign and a word, like this
 
 Then that text and all remaining text up through and including a line
 beginning with C<=cut> will be ignored.  The format of the intervening
-text is described in L<perlpod>. 
+text is described in L<perlpod>.
 
 This allows you to intermix your source code
 and your documentation text freely, as in
 
     =item snazzle($)
 
-    The snazzle() function will behave in the most spectacular 
+    The snazzle() function will behave in the most spectacular
     form that you can possibly imagine, not even excepting
     cybernetic pyrotechnics.
 
@@ -491,11 +502,11 @@ and your documentation text freely, as in
     sub snazzle($) {
        my $thingie = shift;
        .........
-    } 
+    }
 
-Note that pod translators should look at only paragraphs beginning 
+Note that pod translators should look at only paragraphs beginning
 with a pod directive (it makes parsing easier), whereas the compiler
-actually knows to look for pod escapes even in the middle of a 
+actually knows to look for pod escapes even in the middle of a
 paragraph.  This means that the following secret stuff will be
 ignored by both the compiler and the translators.
 
@@ -532,18 +543,18 @@ shell:
     die 'foo';
     __END__
     foo at bzzzt line 201.
-    
+
     % perl
     # line 200 "bzzzt"
     eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
     __END__
     foo at - line 2001.
-    
+
     % perl
     eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
     __END__
     foo at foo bar line 200.
-    
+
     % perl
     # line 345 "goop"
     eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";