perlsub.pod

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

POD
1,150 行
字号
    print "@a has more than @b\n";
    sub func {
	local (*c, *d) = @_;
	if (@c > @d) {
	    return (\@c, \@d);
	} else {
	    return (\@d, \@c);
	}
    }

Here we're using the typeglobs to do symbol table aliasing.  It's
a tad subtle, though, and also won't work if you're using C<my()>
variables, because only globals (well, and C<local()>s) are in the symbol table.

If you're passing around filehandles, you could usually just use the bare
typeglob, like C<*STDOUT>, but typeglobs references would be better because
they'll still work properly under S<C<use strict 'refs'>>.  For example:

    splutter(\*STDOUT);
    sub splutter {
	my $fh = shift;
	print $fh "her um well a hmmm\n";
    }

    $rec = get_rec(\*STDIN);
    sub get_rec {
	my $fh = shift;
	return scalar <$fh>;
    }

Another way to do this is using C<*HANDLE{IO}>, see L<perlref> for usage
and caveats.

If you're planning on generating new filehandles, you could do this:

    sub openit {
	my $name = shift;
	local *FH;
	return open (FH, $path) ? *FH : undef;
    }

Although that will actually produce a small memory leak.  See the bottom
of L<perlfunc/open()> for a somewhat cleaner way using the C<IO::Handle>
package.

=head2 Prototypes

As of the 5.002 release of perl, if you declare

    sub mypush (\@@)

then C<mypush()> takes arguments exactly like C<push()> does.  The declaration
of the function to be called must be visible at compile time.  The prototype
affects only the interpretation of new-style calls to the function, where
new-style is defined as not using the C<&> character.  In other words,
if you call it like a builtin function, then it behaves like a builtin
function.  If you call it like an old-fashioned subroutine, then it
behaves like an old-fashioned subroutine.  It naturally falls out from
this rule that prototypes have no influence on subroutine references
like C<\&foo> or on indirect subroutine calls like C<&{$subref}>.

Method calls are not influenced by prototypes either, because the
function to be called is indeterminate at compile time, because it depends
on inheritance.

Because the intent is primarily to let you define subroutines that work
like builtin commands, here are the prototypes for some other functions
that parse almost exactly like the corresponding builtins.

    Declared as			Called as

    sub mylink ($$)	     mylink $old, $new
    sub myvec ($$$)	     myvec $var, $offset, 1
    sub myindex ($$;$)	     myindex &getstring, "substr"
    sub mysyswrite ($$$;$)   mysyswrite $buf, 0, length($buf) - $off, $off
    sub myreverse (@)	     myreverse $a, $b, $c
    sub myjoin ($@)	     myjoin ":", $a, $b, $c
    sub mypop (\@)	     mypop @array
    sub mysplice (\@$$@)     mysplice @array, @array, 0, @pushme
    sub mykeys (\%)	     mykeys %{$hashref}
    sub myopen (*;$)	     myopen HANDLE, $name
    sub mypipe (**)	     mypipe READHANDLE, WRITEHANDLE
    sub mygrep (&@)	     mygrep { /foo/ } $a, $b, $c
    sub myrand ($)	     myrand 42
    sub mytime ()	     mytime

Any backslashed prototype character represents an actual argument
that absolutely must start with that character.  The value passed
to the subroutine (as part of C<@_>) will be a reference to the
actual argument given in the subroutine call, obtained by applying
C<\> to that argument.

Unbackslashed prototype characters have special meanings.  Any
unbackslashed C<@> or C<%> eats all the rest of the arguments, and forces
list context.  An argument represented by C<$> forces scalar context.  An
C<&> requires an anonymous subroutine, which, if passed as the first
argument, does not require the "C<sub>" keyword or a subsequent comma.  A
C<*> does whatever it has to do to turn the argument into a reference to a
symbol table entry.

A semicolon separates mandatory arguments from optional arguments.
(It is redundant before C<@> or C<%>.)

Note how the last three examples above are treated specially by the parser.
C<mygrep()> is parsed as a true list operator, C<myrand()> is parsed as a
true unary operator with unary precedence the same as C<rand()>, and
C<mytime()> is truly without arguments, just like C<time()>.  That is, if you
say

    mytime +2;

you'll get C<mytime() + 2>, not C<mytime(2)>, which is how it would be parsed
without the prototype.

The interesting thing about C<&> is that you can generate new syntax with it:

    sub try (&@) {
	my($try,$catch) = @_;
	eval { &$try };
	if ($@) {
	    local $_ = $@;
	    &$catch;
	}
    }
    sub catch (&) { $_[0] }

    try {
	die "phooey";
    } catch {
	/phooey/ and print "unphooey\n";
    };

That prints C<"unphooey">.  (Yes, there are still unresolved
issues having to do with the visibility of C<@_>.  I'm ignoring that
question for the moment.  (But note that if we make C<@_> lexically
scoped, those anonymous subroutines can act like closures... (Gee,
is this sounding a little Lispish?  (Never mind.))))

And here's a reimplementation of C<grep>:

    sub mygrep (&@) {
	my $code = shift;
	my @result;
	foreach $_ (@_) {
	    push(@result, $_) if &$code;
	}
	@result;
    }

Some folks would prefer full alphanumeric prototypes.  Alphanumerics have
been intentionally left out of prototypes for the express purpose of
someday in the future adding named, formal parameters.  The current
mechanism's main goal is to let module writers provide better diagnostics
for module users.  Larry feels the notation quite understandable to Perl
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.

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,
if you decide that a function should take just one parameter, like this:

    sub func ($) {
	my $n = shift;
	print "you gave me $n\n";
    }

and someone has been calling it with an array or expression
returning a list:

    func(@foo);
    func( split /:/ );

Then you've just supplied an automatic C<scalar()> in front of their
argument, which can be more than a bit surprising.  The old C<@foo>
which used to hold one thing doesn't get passed in.  Instead,
the C<func()> now gets passed in C<1>, that is, the number of elements
in C<@foo>.  And the C<split()> gets called in a scalar context and
starts scribbling on your C<@_> parameter list.

This is all very powerful, of course, and should be used only in moderation
to make the world a better place.

=head2 Constant Functions

Functions with a prototype of C<()> are potential candidates for
inlining.  If the result after optimization and constant folding is
either a constant or a lexically-scoped scalar which has no other
references, then it will be used in place of function calls made
without C<&> or C<do>. Calls made using C<&> or C<do> are never
inlined.  (See F<constant.pm> for an easy way to declare most
constants.)

The following functions would all be inlined:

    sub pi ()		{ 3.14159 }		# Not exact, but close.
    sub PI ()		{ 4 * atan2 1, 1 }	# As good as it gets,
						# and it's inlined, too!
    sub ST_DEV ()	{ 0 }
    sub ST_INO ()	{ 1 }

    sub FLAG_FOO ()	{ 1 << 8 }
    sub FLAG_BAR ()	{ 1 << 9 }
    sub FLAG_MASK ()	{ FLAG_FOO | FLAG_BAR }

    sub OPT_BAZ ()	{ not (0x1B58 & FLAG_MASK) }
    sub BAZ_VAL () {
	if (OPT_BAZ) {
	    return 23;
	}
	else {
	    return 42;
	}
    }

    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
considered severe enough not to be optional because previously compiled
invocations of the function will still be using the old value of the
function.  If you need to be able to redefine the subroutine you need to
ensure that it isn't inlined, either by dropping the C<()> prototype
(which changes the calling semantics, so beware) or by thwarting the
inlining mechanism in some other way, such as

    sub not_inlined () {
    	23 if $];
    }

=head2 Overriding Builtin Functions

Many builtin functions may be overridden, though this should be tried
only occasionally and for good reason.  Typically this might be
done by a package attempting to emulate missing builtin 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
C<subs> pragma (compiler directive) lets you, in effect, predeclare subs
via the import syntax, and these names may then override the builtin ones:

    use subs 'chdir', 'chroot', 'chmod', 'chown';
    chdir $somewhere;
    sub chdir { ... }

To unambiguously refer to the builtin form, one may precede the
builtin name with the special package qualifier C<CORE::>.  For example,
saying C<CORE::open()> will always refer to the builtin C<open()>, even
if the current package has imported some other subroutine called
C<&open()> from elsewhere.

Library modules should not in general export builtin names like "C<open>"
or "C<chdir>" as part of their default C<@EXPORT> list, because these may
sneak into someone else's namespace and change the semantics unexpectedly.
Instead, if the module adds the name to the C<@EXPORT_OK> list, then it's
possible for a user to import the name explicitly, but not implicitly.
That is, they could say

    use Module 'open';

and it would import the C<open> override, but if they said

    use Module;

they would get the default imports without the overrides.

The foregoing mechanism for overriding builtins is restricted, quite
deliberately, to the package that requests the import.  There is a second
method that is sometimes applicable when you wish to override a builtin
everywhere, without regard to namespace boundaries.  This is achieved by
importing a sub into the special namespace C<CORE::GLOBAL::>.  Here is an
example that quite brazenly replaces the C<glob> operator with something
that understands regular expressions.

    package REGlob;
    require Exporter;
    @ISA = 'Exporter';
    @EXPORT_OK = 'glob';

    sub import {
	my $pkg = shift;
	return unless @_;
	my $sym = shift;
	my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
	$pkg->export($where, $sym, @_);
    }

    sub glob {
	my $pat = shift;
	my @got;
	local(*D);
	if (opendir D, '.') { @got = grep /$pat/, readdir D; closedir D; }
	@got;
    }
    1;

And here's how it could be (ab)used:

    #use REGlob 'GLOBAL_glob';	    # override glob() in ALL namespaces
    package Foo;
    use REGlob 'glob';		    # override glob() in Foo:: only
    print for <^[a-z_]+\.pm\$>;	    # show all pragmatic modules

Note that the initial comment shows a contrived, even dangerous example.
By overriding C<glob> globally, you would be forcing the new (and
subversive) behavior for the C<glob> operator for B<every> namespace,
without the complete cognizance or cooperation of the modules that own
those namespaces.  Naturally, this should be done with extreme caution--if
it must be done at all.

The C<REGlob> example above does not implement all the support needed to
cleanly override perl's C<glob> operator.  The builtin C<glob> has
different behaviors depending on whether it appears in a scalar or list
context, but our C<REGlob> doesn't.  Indeed, many perl builtins have such
context sensitive behaviors, and these must be adequately supported by
a properly written override.  For a fully functional example of overriding
C<glob>, study the implementation of C<File::DosGlob> in the standard
library.


=head2 Autoloading

If you call a subroutine that is undefined, you would ordinarily get an
immediate fatal error complaining that the subroutine doesn't exist.
(Likewise for subroutines being used as methods, when the method
doesn't exist in any base class of the class package.) If,
however, there is an C<AUTOLOAD> subroutine defined in the package or
packages that were searched for the original subroutine, then that
C<AUTOLOAD> subroutine is called with the arguments that would have been
passed to the original subroutine.  The fully qualified name of the
original subroutine magically appears in the C<$AUTOLOAD> variable in 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...

Most C<AUTOLOAD> routines will load in a definition for the subroutine in
question using eval, and then execute that subroutine using a special
form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
without a trace.  (See the standard C<AutoLoader> module, for example.)
But an C<AUTOLOAD> routine can also just emulate the routine and never
define it.   For example, let's pretend that a function that wasn't defined
should just call C<system()> with those arguments.  All you'd do is this:

    sub AUTOLOAD {
	my $program = $AUTOLOAD;
	$program =~ s/.*:://;
	system($program, @_);
    }
    date();
    who('am', 'i');
    ls('-l');

In fact, if you predeclare the functions you want to call that way, you don't
even need the parentheses:

    use subs qw(date who ls);
    date;
    who "am", "i";
    ls -l;

A more complete example of this is the standard Shell module, which
can treat undefined subroutine calls as calls to Unix programs.

Mechanisms are available for modules writers to help split the modules
up into autoloadable files.  See the standard AutoLoader module
described in L<AutoLoader> and in L<AutoSplit>, the standard
SelfLoader modules in L<SelfLoader>, and the document on adding C
functions to perl code in L<perlxs>.

=head1 SEE ALSO

See L<perlref> for more about references and closures.  See L<perlxs> if
you'd like to learn about calling C subroutines from perl.  See L<perlmod>
to learn about bundling up your functions in separate files.

⌨️ 快捷键说明

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