perltrap.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,539 行 · 第 1/3 页

POD
1,539
字号
    # perl4 opens or dies    # perl5 opens FOO, dying only if 'FOO' is false, i.e. never=item * Precedenceperl4 gives the special variable, C<$:> precedence, where perl5treats C<$::> as main C<package>    $a = "x"; print "$::a";    # perl 4 prints: -:a    # perl 5 prints: x=item * Precedenceperl4 had buggy precedence for the file test operators vis-a-visthe assignment operators.  Thus, although the precedence tablefor perl4 leads one to believe C<-e $foo .= "q"> should parse asC<((-e $foo) .= "q")>, it actually parses as C<(-e ($foo .= "q"))>.In perl5, the precedence is as documented.    -e $foo .= "q"    # perl4 prints: no output    # perl5 prints: Can't modify -e in concatenation=item * PrecedenceIn perl4, keys(), each() and values() were special high-precedence operatorsthat operated on a single hash, but in perl5, they are regular named unaryoperators.  As documented, named unary operators have lower precedencethan the arithmetic and concatenation operators C<+ - .>, but the perl4variants of these operators actually bind tighter than C<+ - .>.Thus, for:    %foo = 1..10;    print keys %foo - 1    # perl4 prints: 4    # perl5 prints: Type of arg 1 to keys must be hash (not subtraction)The perl4 behavior was probably more useful, if less consistent.=back=head2 General Regular Expression Traps using s///, etc.All types of RE traps.=over 5=item * Regular ExpressionC<s'$lhs'$rhs'> now does no interpolation on either side.  It used tointerpolate $lhs but not $rhs.  (And still does not match a literal'$' in string)    $a=1;$b=2;    $string = '1 2 $a $b';    $string =~ s'$a'$b';    print $string,"\n";    # perl4 prints: $b 2 $a $b    # perl5 prints: 1 2 $a $b=item * Regular ExpressionC<m//g> now attaches its state to the searched string rather than theregular expression.  (Once the scope of a block is left for the sub, thestate of the searched string is lost)    $_ = "ababab";    while(m/ab/g){        &doit("blah");    }    sub doit{local($_) = shift; print "Got $_ "}    # perl4 prints: Got blah Got blah Got blah Got blah    # perl5 prints: infinite loop blah...=item * Regular ExpressionCurrently, if you use the C<m//o> qualifier on a regular expressionwithin an anonymous sub, I<all> closures generated from that anonymoussub will use the regular expression as it was compiled when it was usedthe very first time in any such closure.  For instance, if you say    sub build_match {        my($left,$right) = @_;        return sub { $_[0] =~ /$left stuff $right/o; };    }    $good = build_match('foo','bar');    $bad = build_match('baz','blarch');    print $good->('foo stuff bar') ? "ok\n" : "not ok\n";    print $bad->('baz stuff blarch') ? "ok\n" : "not ok\n";    print $bad->('foo stuff bar') ? "not ok\n" : "ok\n";For most builds of Perl5, this will print:oknot oknot okbuild_match() will always return a sub which matches the contents of$left and $right as they were the I<first> time that build_match()was called, not as they are in the current call.=item * Regular ExpressionIf no parentheses are used in a match, Perl4 sets C<$+> tothe whole match, just like C<$&>. Perl5 does not.    "abcdef" =~ /b.*e/;    print "\$+ = $+\n";    # perl4 prints: bcde    # perl5 prints:=item * Regular Expressionsubstitution now returns the null string if it fails    $string = "test";    $value = ($string =~ s/foo//);    print $value, "\n";    # perl4 prints: 0    # perl5 prints:Also see L<Numerical Traps> for another example of this new feature.=item * Regular ExpressionC<s`lhs`rhs`> (using backticks) is now a normal substitution, with nobacktick expansion    $string = "";    $string =~ s`^`hostname`;    print $string, "\n";    # perl4 prints: <the local hostname>    # perl5 prints: hostname=item * Regular ExpressionStricter parsing of variables used in regular expressions    s/^([^$grpc]*$grpc[$opt$plus$rep]?)//o;    # perl4: compiles w/o error    # perl5: with Scalar found where operator expected ..., near "$opt$plus"an added component of this example, apparently from the same script, isthe actual value of the s'd string after the substitution.C<[$opt]> is a character class in perl4 and an array subscript in perl5    $grpc = 'a';    $opt  = 'r';    $_ = 'bar';    s/^([^$grpc]*$grpc[$opt]?)/foo/;    print ;    # perl4 prints: foo    # perl5 prints: foobar=item * Regular ExpressionUnder perl5, C<m?x?> matches only once, like C<?x?>. Under perl4, it matchedrepeatedly, like C</x/> or C<m!x!>.    $test = "once";    sub match { $test =~ m?once?; }    &match();    if( &match() ) {        # m?x? matches more then once        print "perl4\n";    } else {        # m?x? matches only once        print "perl5\n";    }    # perl4 prints: perl4    # perl5 prints: perl5=back=head2 Subroutine, Signal, Sorting TrapsThe general group of Perl4-to-Perl5 traps having to do withSignals, Sorting, and their related subroutines, as well asgeneral subroutine traps.  Includes some OS-Specific traps.=over 5=item * (Signals)Barewords that used to look like strings to Perl will now look like subroutinecalls if a subroutine by that name is defined before the compiler sees them.    sub SeeYa { warn"Hasta la vista, baby!" }    $SIG{'TERM'} = SeeYa;    print "SIGTERM is now $SIG{'TERM'}\n";    # perl4 prints: SIGTERM is now main'SeeYa    # perl5 prints: SIGTERM is now main::1 (and warns "Hasta la vista, baby!")Use B<-w> to catch this one=item * (Sort Subroutine)reverse is no longer allowed as the name of a sort subroutine.    sub reverse{ print "yup "; $a <=> $b }    print sort reverse (2,1,3);    # perl4 prints: yup yup 123    # perl5 prints: 123    # perl5 warns (if using -w): Ambiguous call resolved as CORE::reverse()=item * warn() won't let you specify a filehandle.Although it _always_ printed to STDERR, warn() would let you specify afilehandle in perl4.  With perl5 it does not.    warn STDERR "Foo!";    # perl4 prints: Foo!    # perl5 prints: String found where operator expected=back=head2 OS Traps=over 5=item * (SysV)Under HPUX, and some other SysV OSes, one had to reset any signal handler,within  the signal handler function, each time a signal was handled withperl4.  With perl5, the reset is now done correctly.  Any code relyingon the handler _not_ being reset will have to be reworked.Since version 5.002, Perl uses sigaction() under SysV.    sub gotit {        print "Got @_... ";    }    $SIG{'INT'} = 'gotit';    $| = 1;    $pid = fork;    if ($pid) {        kill('INT', $pid);        sleep(1);        kill('INT', $pid);    } else {        while (1) {sleep(10);}    }    # perl4 (HPUX) prints: Got INT...    # perl5 (HPUX) prints: Got INT... Got INT...=item * (SysV)Under SysV OSes, C<seek()> on a file opened to append C<<< >> >>> now doesthe right thing w.r.t. the fopen() manpage. e.g., - When a file is openedfor append,  it  is  impossible to overwrite information already inthe file.    open(TEST,">>seek.test");    $start = tell TEST ;    foreach(1 .. 9){        print TEST "$_ ";    }    $end = tell TEST ;    seek(TEST,$start,0);    print TEST "18 characters here";    # perl4 (solaris) seek.test has: 18 characters here    # perl5 (solaris) seek.test has: 1 2 3 4 5 6 7 8 9 18 characters here=back=head2 Interpolation TrapsPerl4-to-Perl5 traps having to do with how things get interpolatedwithin certain expressions, statements, contexts, or whatever.=over 5=item * Interpolation@ now always interpolates an array in double-quotish strings.    print "To: someone@somewhere.com\n";    # perl4 prints: To:someone@somewhere.com    # perl < 5.6.1, error : In string, @somewhere now must be written as \@somewhere    # perl >= 5.6.1, warning : Possible unintended interpolation of @somewhere in string=item * InterpolationDouble-quoted strings may no longer end with an unescaped $ or @.    $foo = "foo$";    $bar = "bar@";    print "foo is $foo, bar is $bar\n";    # perl4 prints: foo is foo$, bar is bar@    # perl5 errors: Final $ should be \$ or $nameNote: perl5 DOES NOT error on the terminating @ in $bar=item * InterpolationPerl now sometimes evaluates arbitrary expressions inside braces that occurwithin double quotes (usually when the opening brace is preceded by C<$>or C<@>).    @www = "buz";    $foo = "foo";    $bar = "bar";    sub foo { return "bar" };    print "|@{w.w.w}|${main'foo}|";    # perl4 prints: |@{w.w.w}|foo|    # perl5 prints: |buz|bar|Note that you can C<use strict;> to ward off such trappiness under perl5.=item * InterpolationThe construct "this is $$x" used to interpolate the pid at that point, butnow tries to dereference $x.  C<$$> by itself still works fine, however.    $s = "a reference";    $x = *s;    print "this is $$x\n";    # perl4 prints: this is XXXx   (XXX is the current pid)    # perl5 prints: this is a reference=item * InterpolationCreation of hashes on the fly with C<eval "EXPR"> now requires either bothC<$>'s to be protected in the specification of the hash name, or both curliesto be protected.  If both curlies are protected, the result will be compatiblewith perl4 and perl5.  This is a very common practice, and should be changedto use the block form of C<eval{}>  if possible.    $hashname = "foobar";    $key = "baz";    $value = 1234;    eval "\$$hashname{'$key'} = q|$value|";    (defined($foobar{'baz'})) ?  (print "Yup") : (print "Nope");    # perl4 prints: Yup    # perl5 prints: NopeChanging    eval "\$$hashname{'$key'} = q|$value|";to    eval "\$\$hashname{'$key'} = q|$value|";causes the following result:    # perl4 prints: Nope    # perl5 prints: Yupor, changing to    eval "\$$hashname\{'$key'\} = q|$value|";causes the following result:    # perl4 prints: Yup    # perl5 prints: Yup    # and is compatible for both versions=item * Interpolationperl4 programs which unconsciously rely on the bugs in earlier perl versions.    perl -e '$bar=q/not/; print "This is $foo{$bar} perl5"'    # perl4 prints: This is not perl5    # perl5 prints: This is perl5=item * InterpolationYou also have to be careful about array references.    print "$foo{"    perl 4 prints: {    perl 5 prints: syntax error=item * InterpolationSimilarly, watch out for:    $foo = "baz";    print "\$$foo{bar}\n";    # perl4 prints: $baz{bar}    # perl5 prints: $Perl 5 is looking for C<$foo{bar}> which doesn't exist, but perl 4 ishappy just to expand $foo to "baz" by itself.  Watch out for thisespecially in C<eval>'s.=item * InterpolationC<qq()> string passed to C<eval>    eval qq(        foreach \$y (keys %\$x\) {            \$count++;        }    );    # perl4 runs this ok    # perl5 prints: Can't find string terminator ")"=back=head2 DBM TrapsGeneral DBM traps.=over 5=item * DBMExisting dbm databases created under perl4 (or any other dbm/ndbm tool)may cause the same script, run under perl5, to fail.  The build of perl5must have been linked with the same dbm/ndbm as the default for C<dbmopen()>to function properly without C<tie>'ing to an extension dbm implementation.    dbmopen (%dbm, "file", undef);    print "ok\n";    # perl4 prints: ok    # perl5 prints: ok (IFF linked with -ldbm or -lndbm)=item * DBMExisting dbm databases created under perl4 (or any other dbm/ndbm tool)may cause the same script, run under perl5, to fail.  The error generatedwhen exceeding the limit on the key/value size will cause perl5 to exitimmediately.    dbmopen(DB, "testdb",0600) || die "couldn't open db! $!";    $DB{'trap'} = "x" x 1024;  # value too large for most dbm/ndbm    print "YUP\n";    # perl4 prints:    dbm store returned -1, errno 28, key "trap" at - line 3.    YUP    # perl5 prints:    dbm store returned -1, errno 28, key "trap" at - line 3.=back=head2 Unclassified TrapsEverything else.=over 5=item * C<require>/C<do> trap using returned valueIf the file doit.pl has:    sub foo {        $rc = do "./do.pl";        return 8;    }    print &foo, "\n";And the do.pl file has the following single line:    return 3;Running doit.pl gives the following:    # perl 4 prints: 3 (aborts the subroutine early)    # perl 5 prints: 8Same behavior if you replace C<do> with C<require>.=item * C<split> on empty string with LIMIT specified    $string = '';    @list = split(/foo/, $string, 2)Perl4 returns a one element list containing the empty string but Perl5returns an empty list.=backAs always, if any of these are ever officially declared as bugs,they'll be fixed and removed.

⌨️ 快捷键说明

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