perltrap.pod
来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,539 行 · 第 1/3 页
POD
1,539 行
temporary array, but no longer does so (for efficiency). This meansthat you'll now be iterating over the actual values, not over copies ofthe values. Modifications to the loop variable can change the originalvalues. @list = ('ab','abc','bcd','def'); foreach $var (grep(/ab/,@list)){ $var = 1; } print (join(':',@list)); # perl4 prints: ab:abc:bcd:def # perl5 prints: 1:1:bcd:defTo retain Perl4 semantics you need to assign your listexplicitly to a temporary array and then iterate over that. Forexample, you might need to change foreach $var (grep(/ab/,@list)){to foreach $var (@tmp = grep(/ab/,@list)){Otherwise changing $var will clobber the values of @list. (This most oftenhappens when you use C<$_> for the loop variable, and call subroutines inthe loop that don't properly localize C<$_>.)=item * DiscontinuanceC<split> with no arguments now behaves like C<split ' '> (which doesn'treturn an initial null field if $_ starts with whitespace), it used tobehave like C<split /\s+/> (which does). $_ = ' hi mom'; print join(':', split); # perl4 prints: :hi:mom # perl5 prints: hi:mom=item * BugFixPerl 4 would ignore any text which was attached to an B<-e> switch,always taking the code snippet from the following arg. Additionally, itwould silently accept an B<-e> switch without a following arg. Both ofthese behaviors have been fixed. perl -e'print "attached to -e"' 'print "separate arg"' # perl4 prints: separate arg # perl5 prints: attached to -e perl -e # perl4 prints: # perl5 dies: No code specified for -e.=item * DiscontinuanceIn Perl 4 the return value of C<push> was undocumented, but it wasactually the last value being pushed onto the target list. In Perl 5the return value of C<push> is documented, but has changed, it is thenumber of elements in the resulting list. @x = ('existing'); print push(@x, 'first new', 'second new'); # perl4 prints: second new # perl5 prints: 3=item * DeprecationSome error messages will be different.=item * DiscontinuanceIn Perl 4, if in list context the delimiters to the first argument ofC<split()> were C<??>, the result would be placed in C<@_> as well asbeing returned. Perl 5 has more respect for your subroutine arguments.=item * DiscontinuanceSome bugs may have been inadvertently removed. :-)=back=head2 Parsing TrapsPerl4-to-Perl5 traps from having to do with parsing.=over 4=item * ParsingNote the space between . and = $string . = "more string"; print $string; # perl4 prints: more string # perl5 prints: syntax error at - line 1, near ". ="=item * ParsingBetter parsing in perl 5 sub foo {} &foo print("hello, world\n"); # perl4 prints: hello, world # perl5 prints: syntax error=item * Parsing"if it looks like a function, it is a function" rule. print ($foo == 1) ? "is one\n" : "is zero\n"; # perl4 prints: is zero # perl5 warns: "Useless use of a constant in void context" if using -w=item * ParsingString interpolation of the C<$#array> construct differs when bracesare to used around the name. @a = (1..3); print "${#a}"; # perl4 prints: 2 # perl5 fails with syntax error @ = (1..3); print "$#{a}"; # perl4 prints: {a} # perl5 prints: 2=back=head2 Numerical TrapsPerl4-to-Perl5 traps having to do with numerical operators,operands, or output from same.=over 5=item * NumericalFormatted output and significant digits print 7.373504 - 0, "\n"; printf "%20.18f\n", 7.373504 - 0; # Perl4 prints: 7.375039999999996141 7.37503999999999614 # Perl5 prints: 7.373504 7.37503999999999614=item * NumericalThis specific item has been deleted. It demonstrated how the auto-incrementoperator would not catch when a number went over the signed int limit. Fixedin version 5.003_04. But always be wary when using large integers.If in doubt: use Math::BigInt;=item * NumericalAssignment of return values from numeric equality testsdoes not work in perl5 when the test evaluates to false (0).Logical tests now return an null, instead of 0 $p = ($test == 1); print $p,"\n"; # perl4 prints: 0 # perl5 prints:Also see L<"General Regular Expression Traps using s///, etc.">for another example of this new feature...=item * Bitwise string opsWhen bitwise operators which can operate upon either numbers orstrings (C<& | ^ ~>) are given only strings as arguments, perl4 wouldtreat the operands as bitstrings so long as the program contained a callto the C<vec()> function. perl5 treats the string operands as bitstrings.(See L<perlop/Bitwise String Operators> for more details.) $fred = "10"; $barney = "12"; $betty = $fred & $barney; print "$betty\n"; # Uncomment the next line to change perl4's behavior # ($dummy) = vec("dummy", 0, 0); # Perl4 prints: 8 # Perl5 prints: 10 # If vec() is used anywhere in the program, both print: 10=back=head2 General data type trapsPerl4-to-Perl5 traps involving most data-types, and their usagewithin certain expressions and/or context.=over 5=item * (Arrays)Negative array subscripts now count from the end of the array. @a = (1, 2, 3, 4, 5); print "The third element of the array is $a[3] also expressed as $a[-2] \n"; # perl4 prints: The third element of the array is 4 also expressed as # perl5 prints: The third element of the array is 4 also expressed as 4=item * (Arrays)Setting C<$#array> lower now discards array elements, and makes themimpossible to recover. @a = (a,b,c,d,e); print "Before: ",join('',@a); $#a =1; print ", After: ",join('',@a); $#a =3; print ", Recovered: ",join('',@a),"\n"; # perl4 prints: Before: abcde, After: ab, Recovered: abcd # perl5 prints: Before: abcde, After: ab, Recovered: ab=item * (Hashes)Hashes get defined before use local($s,@a,%h); die "scalar \$s defined" if defined($s); die "array \@a defined" if defined(@a); die "hash \%h defined" if defined(%h); # perl4 prints: # perl5 dies: hash %h definedPerl will now generate a warning when it sees defined(@a) anddefined(%h).=item * (Globs)glob assignment from variable to variable will fail if the assignedvariable is localized subsequent to the assignment @a = ("This is Perl 4"); *b = *a; local(@a); print @b,"\n"; # perl4 prints: This is Perl 4 # perl5 prints:=item * (Globs)Assigning C<undef> to a glob has no effect in Perl 5. In Perl 4it undefines the associated scalar (but may have other side effectsincluding SEGVs). Perl 5 will also warn if C<undef> is assigned to atypeglob. (Note that assigning C<undef> to a typeglob is differentthan calling the C<undef> function on a typeglob (C<undef *foo>), whichhas quite a few effects. $foo = "bar"; *foo = undef; print $foo; # perl4 prints: # perl4 warns: "Use of uninitialized variable" if using -w # perl5 prints: bar # perl5 warns: "Undefined value assigned to typeglob" if using -w=item * (Scalar String)Changes in unary negation (of strings)This change effects both the return value and what itdoes to auto(magic)increment. $x = "aaa"; print ++$x," : "; print -$x," : "; print ++$x,"\n"; # perl4 prints: aab : -0 : 1 # perl5 prints: aab : -aab : aac=item * (Constants)perl 4 lets you modify constants: $foo = "x"; &mod($foo); for ($x = 0; $x < 3; $x++) { &mod("a"); } sub mod { print "before: $_[0]"; $_[0] = "m"; print " after: $_[0]\n"; } # perl4: # before: x after: m # before: a after: m # before: m after: m # before: m after: m # Perl5: # before: x after: m # Modification of a read-only value attempted at foo.pl line 12. # before: a=item * (Scalars)The behavior is slightly different for: print "$x", defined $x # perl 4: 1 # perl 5: <no output, $x is not called into existence>=item * (Variable Suicide)Variable suicide behavior is more consistent under Perl 5.Perl5 exhibits the same behavior for hashes and scalars,that perl4 exhibits for only scalars. $aGlobal{ "aKey" } = "global value"; print "MAIN:", $aGlobal{"aKey"}, "\n"; $GlobalLevel = 0; &test( *aGlobal ); sub test { local( *theArgument ) = @_; local( %aNewLocal ); # perl 4 != 5.001l,m $aNewLocal{"aKey"} = "this should never appear"; print "SUB: ", $theArgument{"aKey"}, "\n"; $aNewLocal{"aKey"} = "level $GlobalLevel"; # what should print $GlobalLevel++; if( $GlobalLevel<4 ) { &test( *aNewLocal ); } } # Perl4: # MAIN:global value # SUB: global value # SUB: level 0 # SUB: level 1 # SUB: level 2 # Perl5: # MAIN:global value # SUB: global value # SUB: this should never appear # SUB: this should never appear # SUB: this should never appear=back=head2 Context Traps - scalar, list contexts=over 5=item * (list context)The elements of argument lists for formats are now evaluated in listcontext. This means you can interpolate list values now. @fmt = ("foo","bar","baz"); format STDOUT= @<<<<< @||||| @>>>>> @fmt; . write; # perl4 errors: Please use commas to separate fields in file # perl5 prints: foo bar baz=item * (scalar context)The C<caller()> function now returns a false value in a scalar contextif there is no caller. This lets library files determine if they'rebeing required. caller() ? (print "You rang?\n") : (print "Got a 0\n"); # perl4 errors: There is no caller # perl5 prints: Got a 0=item * (scalar context)The comma operator in a scalar context is now guaranteed to give ascalar context to its arguments. @y= ('a','b','c'); $x = (1, 2, @y); print "x = $x\n"; # Perl4 prints: x = c # Thinks list context interpolates list # Perl5 prints: x = 3 # Knows scalar uses length of list=item * (list, builtin)C<sprintf()> is prototyped as ($;@), so its first argument is given scalarcontext. Thus, if passed an array, it will probably not do what you want,unlike Perl 4: @z = ('%s%s', 'foo', 'bar'); $x = sprintf(@z); print $x; # perl4 prints: foobar # perl5 prints: 3C<printf()> works the same as it did in Perl 4, though: @z = ('%s%s', 'foo', 'bar'); printf STDOUT (@z); # perl4 prints: foobar # perl5 prints: foobar=back=head2 Precedence TrapsPerl4-to-Perl5 traps involving precedence order.Perl 4 has almost the same precedence rules as Perl 5 for the operatorsthat they both have. Perl 4 however, seems to have had someinconsistencies that made the behavior differ from what was documented.=over 5=item * PrecedenceLHS vs. RHS of any assignment operator. LHS is evaluated firstin perl4, second in perl5; this can affect the relationshipbetween side-effects in sub-expressions. @arr = ( 'left', 'right' ); $a{shift @arr} = shift @arr; print join( ' ', keys %a ); # perl4 prints: left # perl5 prints: right=item * PrecedenceThese are now semantic errors because of precedence: @list = (1,2,3,4,5); %map = ("a",1,"b",2,"c",3,"d",4); $n = shift @list + 2; # first item in list plus 2 print "n is $n, "; $m = keys %map + 2; # number of items in hash plus 2 print "m is $m\n"; # perl4 prints: n is 3, m is 6 # perl5 errors and fails to compile=item * PrecedenceThe precedence of assignment operators is now the same as the precedenceof assignment. Perl 4 mistakenly gave them the precedence of the associatedoperator. So you now must parenthesize them in expressions like /foo/ ? ($a += 2) : ($a -= 2);Otherwise /foo/ ? $a += 2 : $a -= 2would be erroneously parsed as (/foo/ ? $a += 2 : $a) -= 2;On the other hand, $a += /foo/ ? 1 : 2;now works as a C programmer would expect.=item * Precedence open FOO || die;is now incorrect. You need parentheses around the filehandle.Otherwise, perl5 leaves the statement as its default precedence: open(FOO || die);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?