Revert change 23843.
[p5sagit/p5-mst-13.2.git] / pod / perlsub.pod
index 2969341..0839f1b 100644 (file)
@@ -67,7 +67,8 @@ Assigning to the whole array C<@_> removes that aliasing, and does
 not update any arguments.
 
 The return value of a subroutine is the value of the last expression
-evaluated.  More explicitly, a C<return> statement may be used to exit the
+evaluated by that sub, or the empty list in the case of an empty sub.
+More explicitly, a C<return> statement may be used to exit the
 subroutine, optionally specifying the returned value, which will be
 evaluated in the appropriate context (list, scalar, or void) depending
 on the context of the subroutine call.  If you specify no return value,
@@ -202,13 +203,17 @@ disables any prototype checking on arguments you do provide.  This
 is partly for historical reasons, and partly for having a convenient way
 to cheat if you know what you're doing.  See L<Prototypes> below.
 
-Functions whose names are in all upper case are reserved to the Perl
-core, as are modules whose names are in all lower case.  A
-function in all capitals is a loosely-held convention meaning it
-will be called indirectly by the run-time system itself, usually
-due to a triggered event.  Functions that do special, pre-defined
-things include C<BEGIN>, C<CHECK>, C<INIT>, C<END>, C<AUTOLOAD>,
-C<CLONE> and C<DESTROY>--plus all functions mentioned in L<perltie>.
+Subroutines whose names are in all upper case are reserved to the Perl
+core, as are modules whose names are in all lower case.  A subroutine in
+all capitals is a loosely-held convention meaning it will be called
+indirectly by the run-time system itself, usually due to a triggered event.
+Subroutines that do special, pre-defined things include C<AUTOLOAD>, C<CLONE>,
+C<DESTROY> plus all functions mentioned in L<perltie> and L<PerlIO::via>.
+
+The C<BEGIN>, C<CHECK>, C<INIT> and C<END> subroutines are not so much
+subroutines as named special code blocks, of which you can have more
+than one in a package, and which you can B<not> call explicitly.  See
+L<perlmod/"BEGIN, CHECK, INIT and END">
 
 =head2 Private Variables via my()
 
@@ -230,7 +235,7 @@ loop (C<for/foreach/while/until/continue>), subroutine, C<eval>,
 or C<do/require/use>'d file.  If more than one value is listed, the
 list must be placed in parentheses.  All listed elements must be
 legal lvalues.  Only alphanumeric identifiers may be lexically
-scoped--magical built-ins like C<$/> must currently be C<local>ize
+scoped--magical built-ins like C<$/> must currently be C<local>ized
 with C<local> instead.
 
 Unlike dynamic variables created by the C<local> operator, lexical
@@ -440,18 +445,18 @@ via C<require> or C<use>, then this is probably just fine.  If it's
 all in the main program, you'll need to arrange for the C<my>
 to be executed early, either by putting the whole block above
 your main program, or more likely, placing merely a C<BEGIN>
-sub around it to make sure it gets executed before your program
+code block around it to make sure it gets executed before your program
 starts to run:
 
-    sub BEGIN {
+    BEGIN {
        my $secret_val = 0;
        sub gimme_another {
            return ++$secret_val;
        }
     }
 
-See L<perlmod/"Package Constructors and Destructors"> about the
-special triggered functions, C<BEGIN>, C<CHECK>, C<INIT> and C<END>.
+See L<perlmod/"BEGIN, CHECK, INIT and END"> about the
+special triggered code blocks, C<BEGIN>, C<CHECK>, C<INIT> and C<END>.
 
 If declared at the outermost scope (the file scope), then lexicals
 work somewhat like C's file statics.  They are available to all
@@ -463,17 +468,24 @@ to create private variables that the whole module can see.
 
 B<WARNING>: In general, you should be using C<my> instead of C<local>, because
 it's faster and safer.  Exceptions to this include the global punctuation
-variables, filehandles and formats, and direct manipulation of the Perl
-symbol table itself.  Format variables often use C<local> though, as do
-other variables whose current value must be visible to called
-subroutines.
+variables, global filehandles and formats, and direct manipulation of the
+Perl symbol table itself.  C<local> is mostly used when the current value
+of a variable must be visible to called subroutines.
 
 Synopsis:
 
-    local $foo;                        # declare $foo dynamically local
-    local (@wid, %get);        # declare list of variables local
-    local $foo = "flurp";      # declare $foo dynamic, and init it
-    local @oof = @bar;         # declare @oof dynamic, and init it
+    # localization of values
+
+    local $foo;                        # make $foo dynamically local
+    local (@wid, %get);                # make list of variables local
+    local $foo = "flurp";      # make $foo dynamic, and init it
+    local @oof = @bar;         # make @oof dynamic, and init it
+
+    local $hash{key} = "val";  # sets a local value for this hash entry
+    local ($cond ? $v1 : $v2); # several types of lvalues support
+                               # localization
+
+    # localization of symbols
 
     local *FH;                 # localize $FH, @FH, %FH, &FH  ...
     local *merlyn = *randal;   # now $merlyn is really $randal, plus
@@ -488,36 +500,26 @@ values to global (meaning package) variables.  It does I<not> create
 a local variable.  This is known as dynamic scoping.  Lexical scoping
 is done with C<my>, which works more like C's auto declarations.
 
-If more than one variable is given to C<local>, they must be placed in
-parentheses.  All listed elements must be legal lvalues.  This operator works
+Some types of lvalues can be localized as well : hash and array elements
+and slices, conditionals (provided that their result is always
+localizable), and symbolic references.  As for simple variables, this
+creates new, dynamically scoped values.
+
+If more than one variable or expression is given to C<local>, they must be
+placed in parentheses.  This operator works
 by saving the current values of those variables in its argument list on a
 hidden stack and restoring them upon exiting the block, subroutine, or
 eval.  This means that called subroutines can also reference the local
 variable, but not the global one.  The argument list may be assigned to if
 desired, which allows you to initialize your local variables.  (If no
 initializer is given for a particular variable, it is created with an
-undefined value.)  Commonly this is used to name the parameters to a
-subroutine.  Examples:
-
-    for $i ( 0 .. 9 ) {
-       $digits{$i} = $i;
-    }
-    # assume this function uses global %digits hash
-    parse_num();
-
-    # now temporarily add to %digits hash
-    if ($base12) {
-       # (NOTE: not claiming this is efficient!)
-       local %digits  = (%digits, 't' => 10, 'e' => 11);
-       parse_num();  # parse_num gets this new %digits!
-    }
-    # old %digits restored here
+undefined value.)
 
 Because C<local> is a run-time operator, it gets executed each time
-through a loop.  In releases of Perl previous to 5.0, this used more stack
-storage each time until the loop was exited.  Perl now reclaims the space
-each time through, but it's still more efficient to declare your variables
-outside the loop.
+through a loop.  Consequently, it's more efficient to localize your
+variables outside the loop.
+
+=head3 Grammatical note on local()
 
 A C<local> is simply a modifier on an lvalue expression.  When you assign to
 a C<local>ized variable, the C<local> doesn't change whether its list is viewed
@@ -532,47 +534,65 @@ both supply a list context to the right-hand side, while
 
 supplies a scalar context.
 
-A note about C<local()> and composite types is in order.  Something
-like C<local(%foo)> works by temporarily placing a brand new hash in
-the symbol table.  The old hash is left alone, but is hidden "behind"
-the new one.
+=head3 Localization of special variables
 
-This means the old variable is completely invisible via the symbol
-table (i.e. the hash entry in the C<*foo> typeglob) for the duration
-of the dynamic scope within which the C<local()> was seen.  This
-has the effect of allowing one to temporarily occlude any magic on
-composite types.  For instance, this will briefly alter a tied
-hash to some other implementation:
+If you localize a special variable, you'll be giving a new value to it,
+but its magic won't go away.  That means that all side-effects related
+to this magic still work with the localized value.
 
-    tie %ahash, 'APackage';
-    [...]
-    {
-       local %ahash;
-       tie %ahash, 'BPackage';
-       [..called code will see %ahash tied to 'BPackage'..]
-       {
-          local %ahash;
-          [..%ahash is a normal (untied) hash here..]
-       }
+This feature allows code like this to work :
+
+    # Read the whole contents of FILE in $slurp
+    { local $/ = undef; $slurp = <FILE>; }
+
+Note, however, that this restricts localization of some values ; for
+example, the following statement dies, as of perl 5.9.0, with an error
+I<Modification of a read-only value attempted>, because the $1 variable is
+magical and read-only :
+
+    local $1 = 2;
+
+Similarly, but in a way more difficult to spot, the following snippet will
+die in perl 5.9.0 :
+
+    sub f { local $_ = "foo"; print }
+    for ($1) {
+       # now $_ is aliased to $1, thus is magic and readonly
+       f();
     }
-    [..%ahash back to its initial tied self again..]
 
-B<WARNING> The code example above does not currently work as described.
+See next section for an alternative to this situation.
+
+B<WARNING>: Localization of tied arrays and hashes does not currently
+work as described.
 This will be fixed in a future release of Perl; in the meantime, avoid
 code that relies on any particular behaviour of localising tied arrays
 or hashes (localising individual elements is still okay).
-See L<perldelta/"Localising Tied Arrays and Hashes Is Broken"> for more
+See L<perl58delta/"Localising Tied Arrays and Hashes Is Broken"> for more
 details.
 
-As another example, a custom implementation of C<%ENV> might look
-like this:
+=head3 Localization of globs
 
-    {
-        local %ENV;
-        tie %ENV, 'MyOwnEnv';
-        [..do your own fancy %ENV manipulation here..]
-    }
-    [..normal %ENV behavior here..]
+The construct
+
+    local *name;
+
+creates a whole new symbol table entry for the glob C<name> in the
+current package.  That means that all variables in its glob slot ($name,
+@name, %name, &name, and the C<name> filehandle) are dynamically reset.
+
+This implies, among other things, that any magic eventually carried by
+those variables is locally lost.  In other words, saying C<local */>
+will not have any effect on the internal value of the input record
+separator.
+
+Notably, if you want to work with a brand new value of the default scalar
+$_, and avoid the potential problem listed above about $_ previously
+carrying a magic value, you should use C<local *_> instead of C<local $_>.
+As of perl 5.9.1, you can also use the lexical form of C<$_> (declaring it
+with C<my $_>), which avoids completely this problem.
+
+=head3 Localization of elements of composite types
 
 It's also worth taking a moment to explain what happens when you
 C<local>ize a member of a composite type (i.e. an array or hash element).
@@ -1114,7 +1134,17 @@ The following functions would all be inlined:
     sub FLAG_MASK ()   { FLAG_FOO | FLAG_BAR }
 
     sub OPT_BAZ ()     { not (0x1B58 & FLAG_MASK) }
-    sub BAZ_VAL () {
+
+    sub N () { int(OPT_BAZ) / 3 }
+
+    sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }
+
+Be aware that these will not be inlined; as they contain inner scopes,
+the constant folding doesn't reduce them to a single constant:
+
+    sub foo_set () { if (FLAG_MASK & FLAG_FOO) { 1 } }
+
+    sub baz_val () {
        if (OPT_BAZ) {
            return 23;
        }
@@ -1123,13 +1153,6 @@ The following functions would all be inlined:
        }
     }
 
-    sub N () { int(BAZ_VAL) / 3 }
-    BEGIN {
-       my $prod = 1;
-       for (1..N) { $prod *= $_ }
-       sub N_FACTORIAL () { $prod }
-    }
-
 If you redefine a subroutine that was eligible for inlining, you'll get
 a mandatory warning.  (You can use this warning to tell whether or not a
 particular subroutine is considered constant.)  The warning is
@@ -1259,7 +1282,7 @@ C<require> replacement as C<require Foo::Bar>, it will actually receive
 the argument C<"Foo/Bar.pm"> in @_.  See L<perlfunc/require>.
 
 And, as you'll have noticed from the previous example, if you override
-C<glob>, the C<E<lt>*E<gt>> glob operator is overridden as well.
+C<glob>, the C<< <*> >> glob operator is overridden as well.
 
 In a similar fashion, overriding the C<readline> function also overrides
 the equivalent I/O operator C<< <FILEHANDLE> >>.
@@ -1279,7 +1302,8 @@ been passed to the original subroutine.  The fully qualified name
 of the original subroutine magically appears in the global $AUTOLOAD
 variable of the same package as the C<AUTOLOAD> routine.  The name
 is not passed as an ordinary argument because, er, well, just
-because, that's why...
+because, that's why.  (As an exception, a method call to a nonexistent
+C<import> or C<unimport> method is just skipped instead.)
 
 Many C<AUTOLOAD> routines load in a definition for the requested
 subroutine using eval(), then execute that subroutine using a special
@@ -1305,7 +1329,7 @@ even need parentheses:
     use subs qw(date who ls);
     date;
     who "am", "i";
-    ls -l;
+    ls '-l';
 
 A more complete example of this is the standard Shell module, which
 can treat undefined subroutine calls as calls to external programs.