perlop.pod

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

POD
1,675 行
字号
is interpreted as an array element C<-9>, not as a regular expression from
variable C<$arr> followed by a digit, which is the interpretation of 
C</$arr[0-9]/>.

Note that absence of processing of C<\\> creates specific restrictions on the
post-processed text: if the delimiter is C</>, one cannot get the combination
C<\/> into the result of this step: C</> will finish the regular expression,
C<\/> will be stripped to C</> on the previous step, and C<\\/> will be left
as is.  Since C</> is equivalent to C<\/> inside a regular expression, this
does not matter unless the delimiter is special character for the RE engine, as 
in C<s*foo*bar*>, C<m[foo]>, or C<?foo?>.

=back

This step is the last one for all the constructs except regular expressions,
which are processed further.

=item Interpolation of regular expressions

All the previous steps were performed during the compilation of Perl code,
this one happens in run time (though it may be optimized to be calculated
at compile time if appropriate).  After all the preprocessing performed 
above (and possibly after evaluation if catenation, joining, up/down-casing 
and C<quotemeta()>ing are involved) the resulting I<string> is passed to RE
engine for compilation.

Whatever happens in the RE engine is better be discussed in L<perlre>,
but for the sake of continuity let us do it here.

This is the first step where presence of the C<//x> switch is relevant.
The RE engine scans the string left-to-right, and converts it to a finite 
automaton.  

Backslashed chars are either substituted by corresponding literal 
strings, or generate special nodes of the finite automaton.  Characters
which are special to the RE engine generate corresponding nodes.  C<(?#...)>
comments are ignored.  All the rest is either converted to literal strings
to match, or is ignored (as is whitespace and C<#>-style comments if
C<//x> is present).

Note that the parsing of the construct C<[...]> is performed using 
absolutely different rules than the rest of the regular expression.  
Similarly, the C<(?{...})> is only checked for matching braces.

=item Optimization of regular expressions

This step is listed for completeness only.  Since it does not change
semantics, details of this step are not documented and are subject
to change.

=back

=head2 I/O Operators

There are several I/O operators you should know about.
A string enclosed by backticks (grave accents) first undergoes
variable substitution just like a double quoted string.  It is then
interpreted as a command, and the output of that command is the value
of the pseudo-literal, like in a shell.  In scalar context, a single
string consisting of all the output is returned.  In list context,
a list of values is returned, one for each line of output.  (You can
set C<$/> to use a different line terminator.)  The command is executed
each time the pseudo-literal is evaluated.  The status value of the
command is returned in C<$?> (see L<perlvar> for the interpretation
of C<$?>).  Unlike in B<csh>, no translation is done on the return
data--newlines remain newlines.  Unlike in any of the shells, single
quotes do not hide variable names in the command from interpretation.
To pass a $ through to the shell you need to hide it with a backslash.
The generalized form of backticks is C<qx//>.  (Because backticks
always undergo shell expansion as well, see L<perlsec> for
security concerns.)

Evaluating a filehandle in angle brackets yields the next line from
that file (newline, if any, included), or C<undef> at end of file.
Ordinarily you must assign that value to a variable, but there is one
situation where an automatic assignment happens.  I<If and ONLY if> the
input symbol is the only thing inside the conditional of a C<while> or
C<for(;;)> loop, the value is automatically assigned to the variable
C<$_>.  In these loop constructs, the assigned value (whether assignment
is automatic or explicit) is then tested to see if it is defined.
The defined test avoids problems where line has a string value
that would be treated as false by perl e.g. "" or "0" with no trailing
newline. (This may seem like an odd thing to you, but you'll use the 
construct in almost every Perl script you write.) Anyway, the following 
lines are equivalent to each other:

    while (defined($_ = <STDIN>)) { print; }
    while ($_ = <STDIN>) { print; }
    while (<STDIN>) { print; }
    for (;<STDIN>;) { print; }
    print while defined($_ = <STDIN>);
    print while ($_ = <STDIN>);
    print while <STDIN>;

and this also behaves similarly, but avoids the use of $_ :

    while (my $line = <STDIN>) { print $line }    

If you really mean such values to terminate the loop they should be 
tested for explicitly:

    while (($_ = <STDIN>) ne '0') { ... }
    while (<STDIN>) { last unless $_; ... }

In other boolean contexts, C<E<lt>I<filehandle>E<gt>> without explicit C<defined>
test or comparison will solicit a warning if C<-w> is in effect.

The filehandles STDIN, STDOUT, and STDERR are predefined.  (The
filehandles C<stdin>, C<stdout>, and C<stderr> will also work except in
packages, where they would be interpreted as local identifiers rather
than global.)  Additional filehandles may be created with the open()
function.  See L<perlfunc/open()> for details on this.

If a E<lt>FILEHANDLEE<gt> is used in a context that is looking for a list, a
list consisting of all the input lines is returned, one line per list
element.  It's easy to make a I<LARGE> data space this way, so use with
care.

The null filehandle E<lt>E<gt> is special and can be used to emulate the
behavior of B<sed> and B<awk>.  Input from E<lt>E<gt> comes either from
standard input, or from each file listed on the command line.  Here's
how it works: the first time E<lt>E<gt> is evaluated, the @ARGV array is
checked, and if it is empty, C<$ARGV[0]> is set to "-", which when opened
gives you standard input.  The @ARGV array is then processed as a list
of filenames.  The loop

    while (<>) {
	...			# code for each line
    }

is equivalent to the following Perl-like pseudo code:

    unshift(@ARGV, '-') unless @ARGV;
    while ($ARGV = shift) {
	open(ARGV, $ARGV);
	while (<ARGV>) {
	    ...		# code for each line
	}
    }

except that it isn't so cumbersome to say, and will actually work.  It
really does shift array @ARGV and put the current filename into variable
$ARGV.  It also uses filehandle I<ARGV> internally--E<lt>E<gt> is just a
synonym for E<lt>ARGVE<gt>, which is magical.  (The pseudo code above
doesn't work because it treats E<lt>ARGVE<gt> as non-magical.)

You can modify @ARGV before the first E<lt>E<gt> as long as the array ends up
containing the list of filenames you really want.  Line numbers (C<$.>)
continue as if the input were one big happy file.  (But see example
under C<eof> for how to reset line numbers on each file.)

If you want to set @ARGV to your own list of files, go right ahead.  
This sets @ARGV to all plain text files if no @ARGV was given:

    @ARGV = grep { -f && -T } glob('*') unless @ARGV;

You can even set them to pipe commands.  For example, this automatically
filters compressed arguments through B<gzip>:

    @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;

If you want to pass switches into your script, you can use one of the
Getopts modules or put a loop on the front like this:

    while ($_ = $ARGV[0], /^-/) {
	shift;
        last if /^--$/;
	if (/^-D(.*)/) { $debug = $1 }
	if (/^-v/)     { $verbose++  }
	# ...		# other switches
    }

    while (<>) {
	# ...		# code for each line
    }

The E<lt>E<gt> symbol will return C<undef> for end-of-file only once.  
If you call it again after this it will assume you are processing another 
@ARGV list, and if you haven't set @ARGV, will input from STDIN.

If the string inside the angle brackets is a reference to a scalar
variable (e.g., E<lt>$fooE<gt>), then that variable contains the name of the
filehandle to input from, or its typeglob, or a reference to the same.  For example:

    $fh = \*STDIN;
    $line = <$fh>;

If what's within the angle brackets is neither a filehandle nor a simple
scalar variable containing a filehandle name, typeglob, or typeglob
reference, it is interpreted as a filename pattern to be globbed, and
either a list of filenames or the next filename in the list is returned,
depending on context.   This distinction is determined on syntactic
grounds alone.  That means C<E<lt>$xE<gt>> is always a readline from
an indirect handle, but C<E<lt>$hash{key}E<gt>> is always a glob.
That's because $x is a simple scalar variable, but C<$hash{key}> is
not--it's a hash element.

One level of double-quote interpretation is done first, but you can't
say C<E<lt>$fooE<gt>> because that's an indirect filehandle as explained
in the previous paragraph.  (In older versions of Perl, programmers
would insert curly brackets to force interpretation as a filename glob:
C<E<lt>${foo}E<gt>>.  These days, it's considered cleaner to call the
internal function directly as C<glob($foo)>, which is probably the right
way to have done it in the first place.)  Example:

    while (<*.c>) {
	chmod 0644, $_;
    }

is equivalent to

    open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
    while (<FOO>) {
	chop;
	chmod 0644, $_;
    }

In fact, it's currently implemented that way.  (Which means it will not
work on filenames with spaces in them unless you have csh(1) on your
machine.)  Of course, the shortest way to do the above is:

    chmod 0644, <*.c>;

Because globbing invokes a shell, it's often faster to call readdir() yourself
and do your own grep() on the filenames.  Furthermore, due to its current
implementation of using a shell, the glob() routine may get "Arg list too
long" errors (unless you've installed tcsh(1L) as F</bin/csh>).

A glob evaluates its (embedded) argument only when it is starting a new
list.  All values must be read before it will start over.  In a list
context this isn't important, because you automatically get them all
anyway.  In scalar context, however, the operator returns the next value
each time it is called, or a C<undef> value if you've just run out. As
for filehandles an automatic C<defined> is generated when the glob
occurs in the test part of a C<while> or C<for> - because legal glob returns
(e.g. a file called F<0>) would otherwise terminate the loop.
Again, C<undef> is returned only once.  So if you're expecting a single value 
from a glob, it is much better to say

    ($file) = <blurch*>;

than

    $file = <blurch*>;

because the latter will alternate between returning a filename and
returning FALSE.

It you're trying to do variable interpolation, it's definitely better
to use the glob() function, because the older notation can cause people
to become confused with the indirect filehandle notation.

    @files = glob("$dir/*.[ch]");
    @files = glob($files[$i]);

=head2 Constant Folding

Like C, Perl does a certain amount of expression evaluation at
compile time, whenever it determines that all arguments to an
operator are static and have no side effects.  In particular, string
concatenation happens at compile time between literals that don't do
variable substitution.  Backslash interpretation also happens at
compile time.  You can say

    'Now is the time for all' . "\n" .
	'good men to come to.'

and this all reduces to one string internally.  Likewise, if
you say

    foreach $file (@filenames) {
	if (-s $file > 5 + 100 * 2**16) {  }
    }

the compiler will precompute the number that
expression represents so that the interpreter
won't have to.

=head2 Bitwise String Operators

Bitstrings of any size may be manipulated by the bitwise operators
(C<~ | & ^>).

If the operands to a binary bitwise op are strings of different sizes,
B<or> and B<xor> ops will act as if the shorter operand had additional
zero bits on the right, while the B<and> op will act as if the longer
operand were truncated to the length of the shorter.

    # ASCII-based examples 
    print "j p \n" ^ " a h";        	# prints "JAPH\n"
    print "JA" | "  ph\n";          	# prints "japh\n"
    print "japh\nJunk" & '_____';   	# prints "JAPH\n";
    print 'p N$' ^ " E<H\n";		# prints "Perl\n";

If you are intending to manipulate bitstrings, you should be certain that
you're supplying bitstrings: If an operand is a number, that will imply
a B<numeric> bitwise operation. You may explicitly show which type of
operation you intend by using C<""> or C<0+>, as in the examples below.

    $foo =  150  |  105 ;	# yields 255  (0x96 | 0x69 is 0xFF)
    $foo = '150' |  105 ;	# yields 255
    $foo =  150  | '105';	# yields 255
    $foo = '150' | '105';	# yields string '155' (under ASCII)

    $baz = 0+$foo & 0+$bar;	# both ops explicitly numeric
    $biz = "$foo" ^ "$bar";	# both ops explicitly stringy

=head2 Integer Arithmetic

By default Perl assumes that it must do most of its arithmetic in
floating point.  But by saying

    use integer;

you may tell the compiler that it's okay to use integer operations
from here to the end of the enclosing BLOCK.  An inner BLOCK may
countermand this by saying

    no integer;

which lasts until the end of that BLOCK.

The bitwise operators ("&", "|", "^", "~", "<<", and ">>") always
produce integral results.  (But see also L<Bitwise String Operators>.)
However, C<use integer> still has meaning
for them.  By default, their results are interpreted as unsigned
integers.  However, if C<use integer> is in effect, their results are
interpreted as signed integers.  For example, C<~0> usually evaluates
to a large integral value.  However, C<use integer; ~0> is -1 on twos-complement machines.

=head2 Floating-point Arithmetic

While C<use integer> provides integer-only arithmetic, there is no
similar ways to provide rounding or truncation at a certain number of
decimal places.  For ro

⌨️ 快捷键说明

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