This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #26839] document the return value of an empty sub
[perl5.git] / pod / perlsub.pod
index f45f549..bfb2909 100644 (file)
@@ -39,7 +39,7 @@ To call subroutines:
 Like many languages, Perl provides for user-defined subroutines.
 These may be located anywhere in the main program, loaded in from
 other files via the C<do>, C<require>, or C<use> keywords, or
-generated on the fly using C<eval> or anonymous subroutines (closures).
+generated on the fly using C<eval> or anonymous subroutines.
 You can even call a function indirectly using a variable containing
 its name or a CODE reference.
 
@@ -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,
@@ -169,8 +170,8 @@ Do not, however, be tempted to do this:
 
 Like the flattened incoming parameter list, the return list is also
 flattened on return.  So all you have managed to do here is stored
-everything in C<@a> and made C<@b> an empty list.  See L<Pass by
-Reference> for alternatives.
+everything in C<@a> and made C<@b> empty.  See 
+L<Pass by Reference> for alternatives.
 
 A subroutine may be called using an explicit C<&> prefix.  The
 C<&> is optional in modern Perl, as are parentheses if the
@@ -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>, 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 explicitely.  See
+L<perlmod/"BEGIN, CHECK, INIT and END">
 
 =head2 Private Variables via my()
 
@@ -220,9 +225,9 @@ Synopsis:
     my @oof = @bar;    # declare @oof lexical, and init it
     my $x : Foo = $y;  # similar, with an attribute applied
 
-B<WARNING>: The use of attribute lists on C<my> declarations is
-experimental.  This feature should not be relied upon.  It may
-change or disappear in future releases of Perl.  See L<attributes>.
+B<WARNING>: The use of attribute lists on C<my> declarations is still
+evolving.  The current semantics and interface are subject to change.
+See L<attributes> and L<Attribute::Handlers>.
 
 The C<my> operator declares the listed variables to be lexically
 confined to the enclosing block, conditional (C<if/unless/elsif/else>),
@@ -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
@@ -325,11 +330,8 @@ it.  Similarly, in the conditional
 
 the scope of $answer extends from its declaration through the rest
 of that conditional, including any C<elsif> and C<else> clauses, 
-but not beyond it.
-
-None of the foregoing text applies to C<if/unless> or C<while/until>
-modifiers appended to simple statements.  Such modifiers are not
-control structures and have no effect on scoping.
+but not beyond it.  See L<perlsyn/"Simple statements"> for information
+on the scope of variables in statements with modifiers.
 
 The C<foreach> loop defaults to scoping its index variable dynamically
 in the manner of C<local>.  However, if the index variable is
@@ -443,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
@@ -466,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
@@ -491,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
@@ -535,40 +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..]
-       }
-    }
-    [..%ahash back to its initial tied self again..]
+This feature allows code like this to work :
 
-As another example, a custom implementation of C<%ENV> might look
-like this:
+    # Read the whole contents of FILE in $slurp
+    { local $/ = undef; $slurp = <FILE>; }
 
-    {
-        local %ENV;
-        tie %ENV, 'MyOwnEnv';
-        [..do your own fancy %ENV manipulation here..]
+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();
     }
-    [..normal %ENV behavior here..]
+
+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<perl58delta/"Localising Tied Arrays and Hashes Is Broken"> for more
+details.
+
+=head3 Localization of globs
+
+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).
@@ -612,14 +636,15 @@ types is subject to change in future.
 
 =head2 Lvalue subroutines
 
-B<WARNING>: Lvalue subroutines are still experimental and the implementation
-may change in future versions of Perl.
+B<WARNING>: Lvalue subroutines are still experimental and the
+implementation may change in future versions of Perl.
 
 It is possible to return a modifiable value from a subroutine.
 To do this, you have to declare the subroutine to return an lvalue.
 
     my $val;
     sub canmod : lvalue {
+       # return $val; this doesn't work, don't say "return"
        $val;
     }
     sub nomod {
@@ -645,9 +670,38 @@ and in:
 
 all the subroutines are called in a list context.
 
-The current implementation does not allow arrays and hashes to be
-returned from lvalue subroutines directly.  You may return a
-reference instead.  This restriction may be lifted in future.
+=over 4
+
+=item Lvalue subroutines are EXPERIMENTAL
+
+They appear to be convenient, but there are several reasons to be
+circumspect.
+
+You can't use the return keyword, you must pass out the value before
+falling out of subroutine scope. (see comment in example above).  This
+is usually not a problem, but it disallows an explicit return out of a
+deeply nested loop, which is sometimes a nice way out.
+
+They violate encapsulation.  A normal mutator can check the supplied
+argument before setting the attribute it is protecting, an lvalue
+subroutine never gets that chance.  Consider;
+
+    my $some_array_ref = [];   # protected by mutators ??
+
+    sub set_arr {              # normal mutator
+       my $val = shift;
+       die("expected array, you supplied ", ref $val)
+          unless ref $val eq 'ARRAY';
+       $some_array_ref = $val;
+    }
+    sub set_arr_lv : lvalue {  # lvalue mutator
+       $some_array_ref;
+    }
+
+    # set_arr_lv cannot stop this !
+    set_arr_lv() = { a => 1 };
+
+=back
 
 =head2 Passing Symbol Table Entries (typeglobs)
 
@@ -697,9 +751,11 @@ Despite the existence of C<my>, there are still three places where the
 C<local> operator still shines.  In fact, in these three places, you
 I<must> use C<local> instead of C<my>.
 
-=over
+=over 4
 
-=item 1. You need to give a global variable a temporary value, especially $_.
+=item 1.
+
+You need to give a global variable a temporary value, especially $_.
 
 The global variables, like C<@ARGV> or the punctuation variables, must be 
 C<local>ized with C<local()>.  This block reads in F</etc/motd>, and splits
@@ -716,7 +772,9 @@ in C<@Fields>.
 It particular, it's important to C<local>ize $_ in any routine that assigns
 to it.  Look out for implicit assignments in C<while> conditionals.
 
-=item 2. You need to create a local file or directory handle or a local function.
+=item 2.
+
+You need to create a local file or directory handle or a local function.
 
 A function that needs a filehandle of its own must use
 C<local()> on a complete typeglob.   This can be used to create new symbol
@@ -724,7 +782,7 @@ table entries:
 
     sub ioqueue {
         local  (*READER, *WRITER);    # not my!
-        pipe    (READER,  WRITER);    or die "pipe: $!";
+        pipe    (READER,  WRITER)     or die "pipe: $!";
         return (*READER, *WRITER);
     }
     ($head, $tail) = ioqueue();
@@ -746,7 +804,9 @@ a local alias.
 See L<perlref/"Function Templates"> for more about manipulating
 functions by name in this way.
 
-=item 3. You want to temporarily change just one element of an array or hash.
+=item 3.
+
+You want to temporarily change just one element of an array or hash.
 
 You can C<local>ize just one element of an aggregate.  Usually this
 is done on dynamics:
@@ -924,6 +984,22 @@ that absolutely must start with that character.  The value passed
 as part of C<@_> will be a reference to the actual argument given
 in the subroutine call, obtained by applying C<\> to that argument.
 
+You can also backslash several argument types simultaneously by using
+the C<\[]> notation:
+
+    sub myref (\[$@%&*])
+
+will allow calling myref() as
+
+    myref $var
+    myref @array
+    myref %hash
+    myref &sub
+    myref *glob
+
+and the first argument of myref() will be a reference to
+a scalar, an array, a hash, a code, or a glob.
+
 Unbackslashed prototype characters have special meanings.  Any
 unbackslashed C<@> or C<%> eats all remaining arguments, and forces
 list context.  An argument represented by C<$> forces scalar context.  An
@@ -1003,6 +1079,13 @@ programmers, and that it will not intrude greatly upon the meat of the
 module, nor make it harder to read.  The line noise is visually
 encapsulated into a small pill that's easy to swallow.
 
+If you try to use an alphanumeric sequence in a prototype you will
+generate an optional warning - "Illegal character in prototype...".
+Unfortunately earlier versions of Perl allowed the prototype to be
+used as long as its prefix was a valid prototype.  The warning may be
+upgraded to a fatal error in a future version of Perl once the
+majority of offending code is fixed.
+
 It's probably best to prototype new functions, not retrofit prototyping
 into older ones.  That's because you must be especially careful about
 silent impositions of differing list versus scalar contexts.  For example,
@@ -1051,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;
        }
@@ -1060,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
@@ -1088,8 +1174,8 @@ only occasionally and for good reason.  Typically this might be
 done by a package attempting to emulate missing built-in functionality
 on a non-Unix system.
 
-Overriding may be done only by importing the name from a
-module--ordinary predeclaration isn't good enough.  However, the
+Overriding may be done only by importing the name from a module at
+compile time--ordinary predeclaration isn't good enough.  However, the
 C<use subs> pragma lets you, in effect, predeclare subs
 via the import syntax, and these names may then override built-in ones:
 
@@ -1176,6 +1262,33 @@ a properly written override.  For a fully functional example of overriding
 C<glob>, study the implementation of C<File::DosGlob> in the standard
 library.
 
+When you override a built-in, your replacement should be consistent (if
+possible) with the built-in native syntax.  You can achieve this by using
+a suitable prototype.  To get the prototype of an overridable built-in,
+use the C<prototype> function with an argument of C<"CORE::builtin_name">
+(see L<perlfunc/prototype>).
+
+Note however that some built-ins can't have their syntax expressed by a
+prototype (such as C<system> or C<chomp>).  If you override them you won't
+be able to fully mimic their original syntax.
+
+The built-ins C<do>, C<require> and C<glob> can also be overridden, but due
+to special magic, their original syntax is preserved, and you don't have
+to define a prototype for their replacements.  (You can't override the
+C<do BLOCK> syntax, though).
+
+C<require> has special additional dark magic: if you invoke your
+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<< <*> >> glob operator is overridden as well.
+
+In a similar fashion, overriding the C<readline> function also overrides
+the equivalent I/O operator C<< <FILEHANDLE> >>.
+
+Finally, some built-ins (e.g. C<exists> or C<grep>) can't be overridden.
+
 =head2 Autoloading
 
 If you call a subroutine that is undefined, you would ordinarily
@@ -1189,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
@@ -1215,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.
@@ -1264,7 +1378,7 @@ parsed and invoked:
     use attributes __PACKAGE__, \&plugh, q[Ugly('\(")], 'Bad';
 
 For further details on attribute lists and their manipulation,
-see L<attributes>.
+see L<attributes> and L<Attribute::Handlers>.
 
 =head1 SEE ALSO