perlsub.pod

来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,150 行 · 第 1/3 页

POD
1,150
字号

Just because a lexical variable is lexically (also called statically)
scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that
within a function it works like a C static.  It normally works more
like a C auto, but with implicit garbage collection.  

Unlike local variables in C or C++, Perl's lexical variables don't
necessarily get recycled just because their scope has exited.
If something more permanent is still aware of the lexical, it will
stick around.  So long as something else references a lexical, that
lexical won't be freed--which is as it should be.  You wouldn't want
memory being free until you were done using it, or kept around once you
were done.  Automatic garbage collection takes care of this for you.

This means that you can pass back or save away references to lexical
variables, whereas to return a pointer to a C auto is a grave error.
It also gives us a way to simulate C's function statics.  Here's a
mechanism for giving a function private variables with both lexical
scoping and a static lifetime.  If you do want to create something like
C's static variables, just enclose the whole function in an extra block,
and put the static variable outside the function but in the block.

    {
	my $secret_val = 0;
	sub gimme_another {
	    return ++$secret_val;
	}
    }
    # $secret_val now becomes unreachable by the outside
    # world, but retains its value between calls to gimme_another

If this function is being sourced in from a separate file
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
starts to run:

    sub BEGIN {
	my $secret_val = 0;
	sub gimme_another {
	    return ++$secret_val;
	}
    }

See L<perlmod/"Package Constructors and Destructors"> about the C<BEGIN> function.

If declared at the outermost scope, the file scope, then lexicals work
someone like C's file statics.  They are available to all functions in
that same file declared below them, but are inaccessible from outside of
the file.  This is sometimes used in modules to create private variables
for the whole module.

=head2 Temporary Values via local()

B<NOTE>: 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.

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

    local *FH;			# localize $FH, @FH, %FH, &FH  ...
    local *merlyn = *randal;	# now $merlyn is really $randal, plus
                                #     @merlyn is really @randal, etc
    local *merlyn = 'randal';	# SAME THING: promote 'randal' to *randal
    local *merlyn = \$randal;   # just alias $merlyn, not @merlyn etc

A C<local()> modifies its listed variables to be "local" to the enclosing
block, C<eval>, or C<do FILE>--and to I<any subroutine called from within that block>.
A C<local()> just gives temporary values to global (meaning package)
variables.  It does B<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
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

Because C<local()> is a run-time command, it gets executed every 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.

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
as a scalar or an array.  So

    local($foo) = <STDIN>;
    local @FOO = <STDIN>;

both supply a list context to the right-hand side, while

    local $foo = <STDIN>;

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.

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:

    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..]

As another example, a custom implementation of C<%ENV> might look
like this:

    {
        local %ENV;
        tie %ENV, 'MyOwnEnv';
        [..do your own fancy %ENV manipulation here..]
    }
    [..normal %ENV behavior here..]

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).
In this case, the element is C<local>ized I<by name>. This means that
when the scope of the C<local()> ends, the saved value will be
restored to the hash element whose key was named in the C<local()>, or
the array element whose index was named in the C<local()>.  If that
element was deleted while the C<local()> was in effect (e.g. by a
C<delete()> from a hash or a C<shift()> of an array), it will spring
back into existence, possibly extending an array and filling in the
skipped elements with C<undef>.  For instance, if you say

    %hash = ( 'This' => 'is', 'a' => 'test' );
    @ary  = ( 0..5 );
    {
         local($ary[5]) = 6;
         local($hash{'a'}) = 'drill';
         while (my $e = pop(@ary)) {
             print "$e . . .\n";
             last unless $e > 3;
         }
         if (@ary) {
             $hash{'only a'} = 'test';
             delete $hash{'a'};
         }
    }
    print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
    print "The array has ",scalar(@ary)," elements: ",
          join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";

Perl will print

    6 . . .
    4 . . .
    3 . . .
    This is a test only a test.
    The array has 6 elements: 0, 1, 2, undef, undef, 5

=head2 Passing Symbol Table Entries (typeglobs)

[Note:  The mechanism described in this section was originally the only
way to simulate pass-by-reference in older versions of Perl.  While it
still works fine in modern versions, the new reference mechanism is
generally easier to work with.  See below.]

Sometimes you don't want to pass the value of an array to a subroutine
but rather the name of it, so that the subroutine can modify the global
copy of it rather than working with a local copy.  In perl you can
refer to all objects of a particular name by prefixing the name
with a star: C<*foo>.  This is often known as a "typeglob", because the
star on the front can be thought of as a wildcard match for all the
funny prefix characters on variables and subroutines and such.

When evaluated, the typeglob produces a scalar value that represents
all the objects of that name, including any filehandle, format, or
subroutine.  When assigned to, it causes the name mentioned to refer to
whatever "C<*>" value was assigned to it.  Example:

    sub doubleary {
	local(*someary) = @_;
	foreach $elem (@someary) {
	    $elem *= 2;
	}
    }
    doubleary(*foo);
    doubleary(*bar);

Note that scalars are already passed by reference, so you can modify
scalar arguments without using this mechanism by referring explicitly
to C<$_[0]> etc.  You can modify all the elements of an array by passing
all the elements as scalars, but you have to use the C<*> mechanism (or
the equivalent reference mechanism) to C<push>, C<pop>, or change the size of
an array.  It will certainly be faster to pass the typeglob (or reference).

Even if you don't want to modify an array, this mechanism is useful for
passing multiple arrays in a single LIST, because normally the LIST
mechanism will merge all the array values so that you can't extract out
the individual arrays.  For more on typeglobs, see
L<perldata/"Typeglobs and Filehandles">.

=head2 When to Still Use local()

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

=item 1. You need to give a global variable a temporary value, especially C<$_>.

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
it up into chunks separated by lines of equal signs, which are placed
in C<@Fields>.

    {
	local @ARGV = ("/etc/motd");
        local $/ = undef;
        local $_ = <>;	
	@Fields = split /^\s*=+\s*$/;
    } 

It particular, it's important to C<local>ize C<$_> 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.

A function that needs a filehandle of its own must use C<local()> uses
C<local()> on complete typeglob.   This can be used to create new symbol
table entries:

    sub ioqueue {
        local  (*READER, *WRITER);    # not my!
        pipe    (READER,  WRITER);    or die "pipe: $!";
        return (*READER, *WRITER);
    }
    ($head, $tail) = ioqueue();

See the Symbol module for a way to create anonymous symbol table
entries.

Because assignment of a reference to a typeglob creates an alias, this
can be used to create what is effectively a local function, or at least,
a local alias.

    {
        local *grow = \&shrink; # only until this block exists
        grow();                 # really calls shrink()
	move();			# if move() grow()s, it shrink()s too
    }
    grow();			# get the real grow() again

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.

You can C<local>ize just one element of an aggregate.  Usually this
is done on dynamics:

    {
	local $SIG{INT} = 'IGNORE';
	funct();			    # uninterruptible
    } 
    # interruptibility automatically restored here

But it also works on lexically declared aggregates.  Prior to 5.005,
this operation could on occasion misbehave.

=back

=head2 Pass by Reference

If you want to pass more than one array or hash into a function--or
return them from it--and have them maintain their integrity, then
you're going to have to use an explicit pass-by-reference.  Before you
do that, you need to understand references as detailed in L<perlref>.
This section may not make much sense to you otherwise.

Here are a few simple examples.  First, let's pass in several
arrays to a function and have it C<pop> all of then, return a new
list of all their former last elements:

    @tailings = popmany ( \@a, \@b, \@c, \@d );

    sub popmany {
	my $aref;
	my @retlist = ();
	foreach $aref ( @_ ) {
	    push @retlist, pop @$aref;
	}
	return @retlist;
    }

Here's how you might write a function that returns a
list of keys occurring in all the hashes passed to it:

    @common = inter( \%foo, \%bar, \%joe );
    sub inter {
	my ($k, $href, %seen); # locals
	foreach $href (@_) {
	    while ( $k = each %$href ) {
		$seen{$k}++;
	    }
	}
	return grep { $seen{$_} == @_ } keys %seen;
    }

So far, we're using just the normal list return mechanism.
What happens if you want to pass or return a hash?  Well,
if you're using only one of them, or you don't mind them
concatenating, then the normal calling convention is ok, although
a little expensive.

Where people get into trouble is here:

    (@a, @b) = func(@c, @d);
or
    (%a, %b) = func(%c, %d);

That syntax simply won't work.  It sets just C<@a> or C<%a> and clears the C<@b> or
C<%b>.  Plus the function didn't get passed into two separate arrays or
hashes: it got one long list in C<@_>, as always.

If you can arrange for everyone to deal with this through references, it's
cleaner code, although not so nice to look at.  Here's a function that
takes two array references as arguments, returning the two array elements
in order of how many elements they have in them:

    ($aref, $bref) = func(\@c, \@d);
    print "@$aref has more than @$bref\n";
    sub func {
	my ($cref, $dref) = @_;
	if (@$cref > @$dref) {
	    return ($cref, $dref);
	} else {
	    return ($dref, $cref);
	}
    }

It turns out that you can actually do this also:

    (*a, *b) = func(\@c, \@d);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?