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 (prototyped to take one scalar parameter) without defining it by saying just:
+subroutine without defining it by saying C<sub name>, thus:
- sub myname ($);
+ sub myname;
$me = myname $0 or die "can't get myname";
-Note that it functions as a list operator though, not as a unary
-operator, so be careful to use C<or> instead of C<||> there.
+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.
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,
unless EXPR
while EXPR
until EXPR
+ foreach EXPR
The C<if> and C<unless> modifiers have the expected semantics,
-presuming you're a speaker of English. The C<while> and C<until>
-modifiers also have the usual "while loop" semantics (conditional
-evaluated first), except when applied to a do-BLOCK (or to the
-now-deprecated do-SUBROUTINE statement), in which case the block
-executes once before the conditional is evaluated. This is so that you
-can write loops like:
+presuming you're a speaker of English. The C<foreach> modifier is an
+iterator: For each value in EXPR, it aliases $_ to the value and
+executes the statement. The C<while> and C<until> modifiers have the
+usual "while loop" semantics (conditional evaluated first), except
+when applied to a do-BLOCK (or to the now-deprecated do-SUBROUTINE
+statement), in which case the block executes once before the
+conditional is evaluated. This is so that you can write loops like:
do {
$line = <STDIN>;
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 |) {}
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
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:
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
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;
}
/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+" }
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.
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.
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'";