1=head1 NAME 2 3perltrap - Perl traps for the unwary 4 5=head1 DESCRIPTION 6 7The biggest trap of all is forgetting to C<use warnings> or use the B<-w> 8switch; see L<perllexwarn> and L<perlrun>. The second biggest trap is not 9making your entire program runnable under C<use strict>. The third biggest 10trap is not reading the list of changes in this version of Perl; see 11L<perldelta>. 12 13=head2 Awk Traps 14 15Accustomed B<awk> users should take special note of the following: 16 17=over 4 18 19=item * 20 21A Perl program executes only once, not once for each input line. You can 22do an implicit loop with C<-n> or C<-p>. 23 24=item * 25 26The English module, loaded via 27 28 use English; 29 30allows you to refer to special variables (like C<$/>) with names (like 31$RS), as though they were in B<awk>; see L<perlvar> for details. 32 33=item * 34 35Semicolons are required after all simple statements in Perl (except 36at the end of a block). Newline is not a statement delimiter. 37 38=item * 39 40Curly brackets are required on C<if>s and C<while>s. 41 42=item * 43 44Variables begin with "$", "@" or "%" in Perl. 45 46=item * 47 48Arrays index from 0. Likewise string positions in substr() and 49index(). 50 51=item * 52 53You have to decide whether your array has numeric or string indices. 54 55=item * 56 57Hash values do not spring into existence upon mere reference. 58 59=item * 60 61You have to decide whether you want to use string or numeric 62comparisons. 63 64=item * 65 66Reading an input line does not split it for you. You get to split it 67to an array yourself. And the split() operator has different 68arguments than B<awk>'s. 69 70=item * 71 72The current input line is normally in $_, not $0. It generally does 73not have the newline stripped. ($0 is the name of the program 74executed.) See L<perlvar>. 75 76=item * 77 78$<I<digit>> does not refer to fields--it refers to substrings matched 79by the last match pattern. 80 81=item * 82 83The print() statement does not add field and record separators unless 84you set C<$,> and C<$\>. You can set $OFS and $ORS if you're using 85the English module. 86 87=item * 88 89You must open your files before you print to them. 90 91=item * 92 93The range operator is "..", not comma. The comma operator works as in 94C. 95 96=item * 97 98The match operator is "=~", not "~". ("~" is the one's complement 99operator, as in C.) 100 101=item * 102 103The exponentiation operator is "**", not "^". "^" is the XOR 104operator, as in C. (You know, one could get the feeling that B<awk> is 105basically incompatible with C.) 106 107=item * 108 109The concatenation operator is ".", not the null string. (Using the 110null string would render C</pat/ /pat/> unparsable, because the third slash 111would be interpreted as a division operator--the tokenizer is in fact 112slightly context sensitive for operators like "/", "?", and ">". 113And in fact, "." itself can be the beginning of a number.) 114 115=item * 116 117The C<next>, C<exit>, and C<continue> keywords work differently. 118 119=item * 120 121 122The following variables work differently: 123 124 Awk Perl 125 ARGC scalar @ARGV (compare with $#ARGV) 126 ARGV[0] $0 127 FILENAME $ARGV 128 FNR $. - something 129 FS (whatever you like) 130 NF $#Fld, or some such 131 NR $. 132 OFMT $# 133 OFS $, 134 ORS $\ 135 RLENGTH length($&) 136 RS $/ 137 RSTART length($`) 138 SUBSEP $; 139 140=item * 141 142You cannot set $RS to a pattern, only a string. 143 144=item * 145 146When in doubt, run the B<awk> construct through B<a2p> and see what it 147gives you. 148 149=back 150 151=head2 C/C++ Traps 152 153Cerebral C and C++ programmers should take note of the following: 154 155=over 4 156 157=item * 158 159Curly brackets are required on C<if>'s and C<while>'s. 160 161=item * 162 163You must use C<elsif> rather than C<else if>. 164 165=item * 166 167The C<break> and C<continue> keywords from C become in Perl C<last> 168and C<next>, respectively. Unlike in C, these do I<not> work within a 169C<do { } while> construct. See L<perlsyn/"Loop Control">. 170 171=item * 172 173The switch statement is called C<given/when> and only available in 174perl 5.10 or newer. See L<perlsyn/"Switch statements">. 175 176=item * 177 178Variables begin with "$", "@" or "%" in Perl. 179 180=item * 181 182Comments begin with "#", not "/*" or "//". Perl may interpret C/C++ 183comments as division operators, unterminated regular expressions or 184the defined-or operator. 185 186=item * 187 188You can't take the address of anything, although a similar operator 189in Perl is the backslash, which creates a reference. 190 191=item * 192 193C<ARGV> must be capitalized. C<$ARGV[0]> is C's C<argv[1]>, and C<argv[0]> 194ends up in C<$0>. 195 196=item * 197 198System calls such as link(), unlink(), rename(), etc. return nonzero for 199success, not 0. (system(), however, returns zero for success.) 200 201=item * 202 203Signal handlers deal with signal names, not numbers. Use C<kill -l> 204to find their names on your system. 205 206=back 207 208=head2 Sed Traps 209 210Seasoned B<sed> programmers should take note of the following: 211 212=over 4 213 214=item * 215 216A Perl program executes only once, not once for each input line. You can 217do an implicit loop with C<-n> or C<-p>. 218 219=item * 220 221Backreferences in substitutions use "$" rather than "\". 222 223=item * 224 225The pattern matching metacharacters "(", ")", and "|" do not have backslashes 226in front. 227 228=item * 229 230The range operator is C<...>, rather than comma. 231 232=back 233 234=head2 Shell Traps 235 236Sharp shell programmers should take note of the following: 237 238=over 4 239 240=item * 241 242The backtick operator does variable interpolation without regard to 243the presence of single quotes in the command. 244 245=item * 246 247The backtick operator does no translation of the return value, unlike B<csh>. 248 249=item * 250 251Shells (especially B<csh>) do several levels of substitution on each 252command line. Perl does substitution in only certain constructs 253such as double quotes, backticks, angle brackets, and search patterns. 254 255=item * 256 257Shells interpret scripts a little bit at a time. Perl compiles the 258entire program before executing it (except for C<BEGIN> blocks, which 259execute at compile time). 260 261=item * 262 263The arguments are available via @ARGV, not $1, $2, etc. 264 265=item * 266 267The environment is not automatically made available as separate scalar 268variables. 269 270=item * 271 272The shell's C<test> uses "=", "!=", "<" etc for string comparisons and "-eq", 273"-ne", "-lt" etc for numeric comparisons. This is the reverse of Perl, which 274uses C<eq>, C<ne>, C<lt> for string comparisons, and C<==>, C<!=> C<< < >> etc 275for numeric comparisons. 276 277=back 278 279=head2 Perl Traps 280 281Practicing Perl Programmers should take note of the following: 282 283=over 4 284 285=item * 286 287Remember that many operations behave differently in a list 288context than they do in a scalar one. See L<perldata> for details. 289 290=item * 291 292Avoid barewords if you can, especially all lowercase ones. 293You can't tell by just looking at it whether a bareword is 294a function or a string. By using quotes on strings and 295parentheses on function calls, you won't ever get them confused. 296 297=item * 298 299You cannot discern from mere inspection which builtins 300are unary operators (like chop() and chdir()) 301and which are list operators (like print() and unlink()). 302(Unless prototyped, user-defined subroutines can B<only> be list 303operators, never unary ones.) See L<perlop> and L<perlsub>. 304 305=item * 306 307People have a hard time remembering that some functions 308default to $_, or @ARGV, or whatever, but that others which 309you might expect to do not. 310 311=item * 312 313The <FH> construct is not the name of the filehandle, it is a readline 314operation on that handle. The data read is assigned to $_ only if the 315file read is the sole condition in a while loop: 316 317 while (<FH>) { } 318 while (defined($_ = <FH>)) { }.. 319 <FH>; # data discarded! 320 321=item * 322 323Remember not to use C<=> when you need C<=~>; 324these two constructs are quite different: 325 326 $x = /foo/; 327 $x =~ /foo/; 328 329=item * 330 331The C<do {}> construct isn't a real loop that you can use 332loop control on. 333 334=item * 335 336Use C<my()> for local variables whenever you can get away with 337it (but see L<perlform> for where you can't). 338Using C<local()> actually gives a local value to a global 339variable, which leaves you open to unforeseen side-effects 340of dynamic scoping. 341 342=item * 343 344If you localize an exported variable in a module, its exported value will 345not change. The local name becomes an alias to a new value but the 346external name is still an alias for the original. 347 348=back 349 350=head2 Perl4 to Perl5 Traps 351 352Practicing Perl4 Programmers should take note of the following 353Perl4-to-Perl5 specific traps. 354 355They're crudely ordered according to the following list: 356 357=over 4 358 359=item Discontinuance, Deprecation, and BugFix traps 360 361Anything that's been fixed as a perl4 bug, removed as a perl4 feature 362or deprecated as a perl4 feature with the intent to encourage usage of 363some other perl5 feature. 364 365=item Parsing Traps 366 367Traps that appear to stem from the new parser. 368 369=item Numerical Traps 370 371Traps having to do with numerical or mathematical operators. 372 373=item General data type traps 374 375Traps involving perl standard data types. 376 377=item Context Traps - scalar, list contexts 378 379Traps related to context within lists, scalar statements/declarations. 380 381=item Precedence Traps 382 383Traps related to the precedence of parsing, evaluation, and execution of 384code. 385 386=item General Regular Expression Traps using s///, etc. 387 388Traps related to the use of pattern matching. 389 390=item Subroutine, Signal, Sorting Traps 391 392Traps related to the use of signals and signal handlers, general subroutines, 393and sorting, along with sorting subroutines. 394 395=item OS Traps 396 397OS-specific traps. 398 399=item DBM Traps 400 401Traps specific to the use of C<dbmopen()>, and specific dbm implementations. 402 403=item Unclassified Traps 404 405Everything else. 406 407=back 408 409If you find an example of a conversion trap that is not listed here, 410please submit it to <F<perlbug@perl.org>> for inclusion. 411Also note that at least some of these can be caught with the 412C<use warnings> pragma or the B<-w> switch. 413 414=head2 Discontinuance, Deprecation, and BugFix traps 415 416Anything that has been discontinued, deprecated, or fixed as 417a bug from perl4. 418 419=over 4 420 421=item * Symbols starting with "_" no longer forced into main 422 423Symbols starting with "_" are no longer forced into package main, except 424for C<$_> itself (and C<@_>, etc.). 425 426 package test; 427 $_legacy = 1; 428 429 package main; 430 print "\$_legacy is ",$_legacy,"\n"; 431 432 # perl4 prints: $_legacy is 1 433 # perl5 prints: $_legacy is 434 435=item * Double-colon valid package separator in variable name 436 437Double-colon is now a valid package separator in a variable name. Thus these 438behave differently in perl4 vs. perl5, because the packages don't exist. 439 440 $a=1;$b=2;$c=3;$var=4; 441 print "$a::$b::$c "; 442 print "$var::abc::xyz\n"; 443 444 # perl4 prints: 1::2::3 4::abc::xyz 445 # perl5 prints: 3 446 447Given that C<::> is now the preferred package delimiter, it is debatable 448whether this should be classed as a bug or not. 449(The older package delimiter, ' ,is used here) 450 451 $x = 10; 452 print "x=${'x}\n"; 453 454 # perl4 prints: x=10 455 # perl5 prints: Can't find string terminator "'" anywhere before EOF 456 457You can avoid this problem, and remain compatible with perl4, if you 458always explicitly include the package name: 459 460 $x = 10; 461 print "x=${main'x}\n"; 462 463Also see precedence traps, for parsing C<$:>. 464 465=item * 2nd and 3rd args to C<splice()> are now in scalar context 466 467The second and third arguments of C<splice()> are now evaluated in scalar 468context (as the Camel says) rather than list context. 469 470 sub sub1{return(0,2) } # return a 2-element list 471 sub sub2{ return(1,2,3)} # return a 3-element list 472 @a1 = ("a","b","c","d","e"); 473 @a2 = splice(@a1,&sub1,&sub2); 474 print join(' ',@a2),"\n"; 475 476 # perl4 prints: a b 477 # perl5 prints: c d e 478 479=item * Can't do C<goto> into a block that is optimized away 480 481You can't do a C<goto> into a block that is optimized away. Darn. 482 483 goto marker1; 484 485 for(1){ 486 marker1: 487 print "Here I is!\n"; 488 } 489 490 # perl4 prints: Here I is! 491 # perl5 errors: Can't "goto" into the middle of a foreach loop 492 493=item * Can't use whitespace as variable name or quote delimiter 494 495It is no longer syntactically legal to use whitespace as the name 496of a variable, or as a delimiter for any kind of quote construct. 497Double darn. 498 499 $a = ("foo bar"); 500 $b = q baz; 501 print "a is $a, b is $b\n"; 502 503 # perl4 prints: a is foo bar, b is baz 504 # perl5 errors: Bareword found where operator expected 505 506=item * C<while/if BLOCK BLOCK> gone 507 508The archaic while/if BLOCK BLOCK syntax is no longer supported. 509 510 if { 1 } { 511 print "True!"; 512 } 513 else { 514 print "False!"; 515 } 516 517 # perl4 prints: True! 518 # perl5 errors: syntax error at test.pl line 1, near "if {" 519 520=item * C<**> binds tighter than unary minus 521 522The C<**> operator now binds more tightly than unary minus. 523It was documented to work this way before, but didn't. 524 525 print -4**2,"\n"; 526 527 # perl4 prints: 16 528 # perl5 prints: -16 529 530=item * C<foreach> changed when iterating over a list 531 532The meaning of C<foreach{}> has changed slightly when it is iterating over a 533list which is not an array. This used to assign the list to a 534temporary array, but no longer does so (for efficiency). This means 535that you'll now be iterating over the actual values, not over copies of 536the values. Modifications to the loop variable can change the original 537values. 538 539 @list = ('ab','abc','bcd','def'); 540 foreach $var (grep(/ab/,@list)){ 541 $var = 1; 542 } 543 print (join(':',@list)); 544 545 # perl4 prints: ab:abc:bcd:def 546 # perl5 prints: 1:1:bcd:def 547 548To retain Perl4 semantics you need to assign your list 549explicitly to a temporary array and then iterate over that. For 550example, you might need to change 551 552 foreach $var (grep(/ab/,@list)){ 553 554to 555 556 foreach $var (@tmp = grep(/ab/,@list)){ 557 558Otherwise changing $var will clobber the values of @list. (This most often 559happens when you use C<$_> for the loop variable, and call subroutines in 560the loop that don't properly localize C<$_>.) 561 562=item * C<split> with no args behavior changed 563 564C<split> with no arguments now behaves like C<split ' '> (which doesn't 565return an initial null field if $_ starts with whitespace), it used to 566behave like C<split /\s+/> (which does). 567 568 $_ = ' hi mom'; 569 print join(':', split); 570 571 # perl4 prints: :hi:mom 572 # perl5 prints: hi:mom 573 574=item * B<-e> behavior fixed 575 576Perl 4 would ignore any text which was attached to an B<-e> switch, 577always taking the code snippet from the following arg. Additionally, it 578would silently accept an B<-e> switch without a following arg. Both of 579these behaviors have been fixed. 580 581 perl -e'print "attached to -e"' 'print "separate arg"' 582 583 # perl4 prints: separate arg 584 # perl5 prints: attached to -e 585 586 perl -e 587 588 # perl4 prints: 589 # perl5 dies: No code specified for -e. 590 591=item * C<push> returns number of elements in resulting list 592 593In Perl 4 the return value of C<push> was undocumented, but it was 594actually the last value being pushed onto the target list. In Perl 5 595the return value of C<push> is documented, but has changed, it is the 596number of elements in the resulting list. 597 598 @x = ('existing'); 599 print push(@x, 'first new', 'second new'); 600 601 # perl4 prints: second new 602 # perl5 prints: 3 603 604=item * Some error messages differ 605 606Some error messages will be different. 607 608=item * C<split()> honors subroutine args 609 610In Perl 4, if in list context the delimiters to the first argument of 611C<split()> were C<??>, the result would be placed in C<@_> as well as 612being returned. Perl 5 has more respect for your subroutine arguments. 613 614=item * Bugs removed 615 616Some bugs may have been inadvertently removed. :-) 617 618=back 619 620=head2 Parsing Traps 621 622Perl4-to-Perl5 traps from having to do with parsing. 623 624=over 4 625 626=item * Space between . and = triggers syntax error 627 628Note the space between . and = 629 630 $string . = "more string"; 631 print $string; 632 633 # perl4 prints: more string 634 # perl5 prints: syntax error at - line 1, near ". =" 635 636=item * Better parsing in perl 5 637 638Better parsing in perl 5 639 640 sub foo {} 641 &foo 642 print("hello, world\n"); 643 644 # perl4 prints: hello, world 645 # perl5 prints: syntax error 646 647=item * Function parsing 648 649"if it looks like a function, it is a function" rule. 650 651 print 652 ($foo == 1) ? "is one\n" : "is zero\n"; 653 654 # perl4 prints: is zero 655 # perl5 warns: "Useless use of a constant in void context" if using -w 656 657=item * String interpolation of C<$#array> differs 658 659String interpolation of the C<$#array> construct differs when braces 660are to used around the name. 661 662 @a = (1..3); 663 print "${#a}"; 664 665 # perl4 prints: 2 666 # perl5 fails with syntax error 667 668 @ = (1..3); 669 print "$#{a}"; 670 671 # perl4 prints: {a} 672 # perl5 prints: 2 673 674=item * Perl guesses on C<map>, C<grep> followed by C<{> if it starts BLOCK or hash ref 675 676When perl sees C<map {> (or C<grep {>), it has to guess whether the C<{> 677starts a BLOCK or a hash reference. If it guesses wrong, it will report 678a syntax error near the C<}> and the missing (or unexpected) comma. 679 680Use unary C<+> before C<{> on a hash reference, and unary C<+> applied 681to the first thing in a BLOCK (after C<{>), for perl to guess right all 682the time. (See L<perlfunc/map>.) 683 684=back 685 686=head2 Numerical Traps 687 688Perl4-to-Perl5 traps having to do with numerical operators, 689operands, or output from same. 690 691=over 5 692 693=item * Formatted output and significant digits 694 695Formatted output and significant digits. In general, Perl 5 696tries to be more precise. For example, on a Solaris Sparc: 697 698 print 7.373504 - 0, "\n"; 699 printf "%20.18f\n", 7.373504 - 0; 700 701 # Perl4 prints: 702 7.3750399999999996141 703 7.375039999999999614 704 705 # Perl5 prints: 706 7.373504 707 7.375039999999999614 708 709Notice how the first result looks better in Perl 5. 710 711Your results may vary, since your floating point formatting routines 712and even floating point format may be slightly different. 713 714=item * Auto-increment operator over signed int limit deleted 715 716This specific item has been deleted. It demonstrated how the auto-increment 717operator would not catch when a number went over the signed int limit. Fixed 718in version 5.003_04. But always be wary when using large integers. 719If in doubt: 720 721 use Math::BigInt; 722 723=item * Assignment of return values from numeric equality tests doesn't work 724 725Assignment of return values from numeric equality tests 726does not work in perl5 when the test evaluates to false (0). 727Logical tests now return a null, instead of 0 728 729 $p = ($test == 1); 730 print $p,"\n"; 731 732 # perl4 prints: 0 733 # perl5 prints: 734 735Also see L<"General Regular Expression Traps using s///, etc."> 736for another example of this new feature... 737 738=item * Bitwise string ops 739 740When bitwise operators which can operate upon either numbers or 741strings (C<& | ^ ~>) are given only strings as arguments, perl4 would 742treat the operands as bitstrings so long as the program contained a call 743to the C<vec()> function. perl5 treats the string operands as bitstrings. 744(See L<perlop/Bitwise String Operators> for more details.) 745 746 $fred = "10"; 747 $barney = "12"; 748 $betty = $fred & $barney; 749 print "$betty\n"; 750 # Uncomment the next line to change perl4's behavior 751 # ($dummy) = vec("dummy", 0, 0); 752 753 # Perl4 prints: 754 8 755 756 # Perl5 prints: 757 10 758 759 # If vec() is used anywhere in the program, both print: 760 10 761 762=back 763 764=head2 General data type traps 765 766Perl4-to-Perl5 traps involving most data-types, and their usage 767within certain expressions and/or context. 768 769=over 5 770 771=item * Negative array subscripts now count from the end of array 772 773Negative array subscripts now count from the end of the array. 774 775 @a = (1, 2, 3, 4, 5); 776 print "The third element of the array is $a[3] also expressed as $a[-2] \n"; 777 778 # perl4 prints: The third element of the array is 4 also expressed as 779 # perl5 prints: The third element of the array is 4 also expressed as 4 780 781=item * Setting C<$#array> lower now discards array elements 782 783Setting C<$#array> lower now discards array elements, and makes them 784impossible to recover. 785 786 @a = (a,b,c,d,e); 787 print "Before: ",join('',@a); 788 $#a =1; 789 print ", After: ",join('',@a); 790 $#a =3; 791 print ", Recovered: ",join('',@a),"\n"; 792 793 # perl4 prints: Before: abcde, After: ab, Recovered: abcd 794 # perl5 prints: Before: abcde, After: ab, Recovered: ab 795 796=item * Hashes get defined before use 797 798Hashes get defined before use 799 800 local($s,@a,%h); 801 die "scalar \$s defined" if defined($s); 802 die "array \@a defined" if defined(@a); 803 die "hash \%h defined" if defined(%h); 804 805 # perl4 prints: 806 # perl5 dies: hash %h defined 807 808Perl will now generate a warning when it sees defined(@a) and 809defined(%h). 810 811=item * Glob assignment from localized variable to variable 812 813glob assignment from variable to variable will fail if the assigned 814variable is localized subsequent to the assignment 815 816 @a = ("This is Perl 4"); 817 *b = *a; 818 local(@a); 819 print @b,"\n"; 820 821 # perl4 prints: This is Perl 4 822 # perl5 prints: 823 824=item * Assigning C<undef> to glob 825 826Assigning C<undef> to a glob has no effect in Perl 5. In Perl 4 827it undefines the associated scalar (but may have other side effects 828including SEGVs). Perl 5 will also warn if C<undef> is assigned to a 829typeglob. (Note that assigning C<undef> to a typeglob is different 830than calling the C<undef> function on a typeglob (C<undef *foo>), which 831has quite a few effects. 832 833 $foo = "bar"; 834 *foo = undef; 835 print $foo; 836 837 # perl4 prints: 838 # perl4 warns: "Use of uninitialized variable" if using -w 839 # perl5 prints: bar 840 # perl5 warns: "Undefined value assigned to typeglob" if using -w 841 842=item * Changes in unary negation (of strings) 843 844Changes in unary negation (of strings) 845This change effects both the return value and what it 846does to auto(magic)increment. 847 848 $x = "aaa"; 849 print ++$x," : "; 850 print -$x," : "; 851 print ++$x,"\n"; 852 853 # perl4 prints: aab : -0 : 1 854 # perl5 prints: aab : -aab : aac 855 856=item * Modifying of constants prohibited 857 858perl 4 lets you modify constants: 859 860 $foo = "x"; 861 &mod($foo); 862 for ($x = 0; $x < 3; $x++) { 863 &mod("a"); 864 } 865 sub mod { 866 print "before: $_[0]"; 867 $_[0] = "m"; 868 print " after: $_[0]\n"; 869 } 870 871 # perl4: 872 # before: x after: m 873 # before: a after: m 874 # before: m after: m 875 # before: m after: m 876 877 # Perl5: 878 # before: x after: m 879 # Modification of a read-only value attempted at foo.pl line 12. 880 # before: a 881 882=item * C<defined $var> behavior changed 883 884The behavior is slightly different for: 885 886 print "$x", defined $x 887 888 # perl 4: 1 889 # perl 5: <no output, $x is not called into existence> 890 891=item * Variable Suicide 892 893Variable suicide behavior is more consistent under Perl 5. 894Perl5 exhibits the same behavior for hashes and scalars, 895that perl4 exhibits for only scalars. 896 897 $aGlobal{ "aKey" } = "global value"; 898 print "MAIN:", $aGlobal{"aKey"}, "\n"; 899 $GlobalLevel = 0; 900 &test( *aGlobal ); 901 902 sub test { 903 local( *theArgument ) = @_; 904 local( %aNewLocal ); # perl 4 != 5.001l,m 905 $aNewLocal{"aKey"} = "this should never appear"; 906 print "SUB: ", $theArgument{"aKey"}, "\n"; 907 $aNewLocal{"aKey"} = "level $GlobalLevel"; # what should print 908 $GlobalLevel++; 909 if( $GlobalLevel<4 ) { 910 &test( *aNewLocal ); 911 } 912 } 913 914 # Perl4: 915 # MAIN:global value 916 # SUB: global value 917 # SUB: level 0 918 # SUB: level 1 919 # SUB: level 2 920 921 # Perl5: 922 # MAIN:global value 923 # SUB: global value 924 # SUB: this should never appear 925 # SUB: this should never appear 926 # SUB: this should never appear 927 928=back 929 930=head2 Context Traps - scalar, list contexts 931 932=over 5 933 934=item * Elements of argument lists for formats evaluated in list context 935 936The elements of argument lists for formats are now evaluated in list 937context. This means you can interpolate list values now. 938 939 @fmt = ("foo","bar","baz"); 940 format STDOUT= 941 @<<<<< @||||| @>>>>> 942 @fmt; 943 . 944 write; 945 946 # perl4 errors: Please use commas to separate fields in file 947 # perl5 prints: foo bar baz 948 949=item * C<caller()> returns false value in scalar context if no caller present 950 951The C<caller()> function now returns a false value in a scalar context 952if there is no caller. This lets library files determine if they're 953being required. 954 955 caller() ? (print "You rang?\n") : (print "Got a 0\n"); 956 957 # perl4 errors: There is no caller 958 # perl5 prints: Got a 0 959 960=item * Comma operator in scalar context gives scalar context to args 961 962The comma operator in a scalar context is now guaranteed to give a 963scalar context to its arguments. 964 965 @y= ('a','b','c'); 966 $x = (1, 2, @y); 967 print "x = $x\n"; 968 969 # Perl4 prints: x = c # Thinks list context interpolates list 970 # Perl5 prints: x = 3 # Knows scalar uses length of list 971 972=item * C<sprintf()> prototyped as C<($;@)> 973 974C<sprintf()> is prototyped as ($;@), so its first argument is given scalar 975context. Thus, if passed an array, it will probably not do what you want, 976unlike Perl 4: 977 978 @z = ('%s%s', 'foo', 'bar'); 979 $x = sprintf(@z); 980 print $x; 981 982 # perl4 prints: foobar 983 # perl5 prints: 3 984 985C<printf()> works the same as it did in Perl 4, though: 986 987 @z = ('%s%s', 'foo', 'bar'); 988 printf STDOUT (@z); 989 990 # perl4 prints: foobar 991 # perl5 prints: foobar 992 993=back 994 995=head2 Precedence Traps 996 997Perl4-to-Perl5 traps involving precedence order. 998 999Perl 4 has almost the same precedence rules as Perl 5 for the operators 1000that they both have. Perl 4 however, seems to have had some 1001inconsistencies that made the behavior differ from what was documented. 1002 1003=over 5 1004 1005=item * LHS vs. RHS of any assignment operator 1006 1007LHS vs. RHS of any assignment operator. LHS is evaluated first 1008in perl4, second in perl5; this can affect the relationship 1009between side-effects in sub-expressions. 1010 1011 @arr = ( 'left', 'right' ); 1012 $a{shift @arr} = shift @arr; 1013 print join( ' ', keys %a ); 1014 1015 # perl4 prints: left 1016 # perl5 prints: right 1017 1018=item * Semantic errors introduced due to precedence 1019 1020These are now semantic errors because of precedence: 1021 1022 @list = (1,2,3,4,5); 1023 %map = ("a",1,"b",2,"c",3,"d",4); 1024 $n = shift @list + 2; # first item in list plus 2 1025 print "n is $n, "; 1026 $m = keys %map + 2; # number of items in hash plus 2 1027 print "m is $m\n"; 1028 1029 # perl4 prints: n is 3, m is 6 1030 # perl5 errors and fails to compile 1031 1032=item * Precedence of assignment operators same as the precedence of assignment 1033 1034The precedence of assignment operators is now the same as the precedence 1035of assignment. Perl 4 mistakenly gave them the precedence of the associated 1036operator. So you now must parenthesize them in expressions like 1037 1038 /foo/ ? ($a += 2) : ($a -= 2); 1039 1040Otherwise 1041 1042 /foo/ ? $a += 2 : $a -= 2 1043 1044would be erroneously parsed as 1045 1046 (/foo/ ? $a += 2 : $a) -= 2; 1047 1048On the other hand, 1049 1050 $a += /foo/ ? 1 : 2; 1051 1052now works as a C programmer would expect. 1053 1054=item * C<open> requires parentheses around filehandle 1055 1056 open FOO || die; 1057 1058is now incorrect. You need parentheses around the filehandle. 1059Otherwise, perl5 leaves the statement as its default precedence: 1060 1061 open(FOO || die); 1062 1063 # perl4 opens or dies 1064 # perl5 opens FOO, dying only if 'FOO' is false, i.e. never 1065 1066=item * C<$:> precedence over C<$::> gone 1067 1068perl4 gives the special variable, C<$:> precedence, where perl5 1069treats C<$::> as main C<package> 1070 1071 $a = "x"; print "$::a"; 1072 1073 # perl 4 prints: -:a 1074 # perl 5 prints: x 1075 1076=item * Precedence of file test operators documented 1077 1078perl4 had buggy precedence for the file test operators vis-a-vis 1079the assignment operators. Thus, although the precedence table 1080for perl4 leads one to believe C<-e $foo .= "q"> should parse as 1081C<((-e $foo) .= "q")>, it actually parses as C<(-e ($foo .= "q"))>. 1082In perl5, the precedence is as documented. 1083 1084 -e $foo .= "q" 1085 1086 # perl4 prints: no output 1087 # perl5 prints: Can't modify -e in concatenation 1088 1089=item * C<keys>, C<each>, C<values> are regular named unary operators 1090 1091In perl4, keys(), each() and values() were special high-precedence operators 1092that operated on a single hash, but in perl5, they are regular named unary 1093operators. As documented, named unary operators have lower precedence 1094than the arithmetic and concatenation operators C<+ - .>, but the perl4 1095variants of these operators actually bind tighter than C<+ - .>. 1096Thus, for: 1097 1098 %foo = 1..10; 1099 print keys %foo - 1 1100 1101 # perl4 prints: 4 1102 # perl5 prints: Type of arg 1 to keys must be hash (not subtraction) 1103 1104The perl4 behavior was probably more useful, if less consistent. 1105 1106=back 1107 1108=head2 General Regular Expression Traps using s///, etc. 1109 1110All types of RE traps. 1111 1112=over 5 1113 1114=item * C<s'$lhs'$rhs'> interpolates on either side 1115 1116C<s'$lhs'$rhs'> now does no interpolation on either side. It used to 1117interpolate $lhs but not $rhs. (And still does not match a literal 1118'$' in string) 1119 1120 $a=1;$b=2; 1121 $string = '1 2 $a $b'; 1122 $string =~ s'$a'$b'; 1123 print $string,"\n"; 1124 1125 # perl4 prints: $b 2 $a $b 1126 # perl5 prints: 1 2 $a $b 1127 1128=item * C<m//g> attaches its state to the searched string 1129 1130C<m//g> now attaches its state to the searched string rather than the 1131regular expression. (Once the scope of a block is left for the sub, the 1132state of the searched string is lost) 1133 1134 $_ = "ababab"; 1135 while(m/ab/g){ 1136 &doit("blah"); 1137 } 1138 sub doit{local($_) = shift; print "Got $_ "} 1139 1140 # perl4 prints: Got blah Got blah Got blah Got blah 1141 # perl5 prints: infinite loop blah... 1142 1143=item * C<m//o> used within an anonymous sub 1144 1145Currently, if you use the C<m//o> qualifier on a regular expression 1146within an anonymous sub, I<all> closures generated from that anonymous 1147sub will use the regular expression as it was compiled when it was used 1148the very first time in any such closure. For instance, if you say 1149 1150 sub build_match { 1151 my($left,$right) = @_; 1152 return sub { $_[0] =~ /$left stuff $right/o; }; 1153 } 1154 $good = build_match('foo','bar'); 1155 $bad = build_match('baz','blarch'); 1156 print $good->('foo stuff bar') ? "ok\n" : "not ok\n"; 1157 print $bad->('baz stuff blarch') ? "ok\n" : "not ok\n"; 1158 print $bad->('foo stuff bar') ? "not ok\n" : "ok\n"; 1159 1160For most builds of Perl5, this will print: 1161ok 1162not ok 1163not ok 1164 1165build_match() will always return a sub which matches the contents of 1166$left and $right as they were the I<first> time that build_match() 1167was called, not as they are in the current call. 1168 1169=item * C<$+> isn't set to whole match 1170 1171If no parentheses are used in a match, Perl4 sets C<$+> to 1172the whole match, just like C<$&>. Perl5 does not. 1173 1174 "abcdef" =~ /b.*e/; 1175 print "\$+ = $+\n"; 1176 1177 # perl4 prints: bcde 1178 # perl5 prints: 1179 1180=item * Substitution now returns null string if it fails 1181 1182substitution now returns the null string if it fails 1183 1184 $string = "test"; 1185 $value = ($string =~ s/foo//); 1186 print $value, "\n"; 1187 1188 # perl4 prints: 0 1189 # perl5 prints: 1190 1191Also see L<Numerical Traps> for another example of this new feature. 1192 1193=item * C<s`lhs`rhs`> is now a normal substitution 1194 1195C<s`lhs`rhs`> (using backticks) is now a normal substitution, with no 1196backtick expansion 1197 1198 $string = ""; 1199 $string =~ s`^`hostname`; 1200 print $string, "\n"; 1201 1202 # perl4 prints: <the local hostname> 1203 # perl5 prints: hostname 1204 1205=item * Stricter parsing of variables in regular expressions 1206 1207Stricter parsing of variables used in regular expressions 1208 1209 s/^([^$grpc]*$grpc[$opt$plus$rep]?)//o; 1210 1211 # perl4: compiles w/o error 1212 # perl5: with Scalar found where operator expected ..., near "$opt$plus" 1213 1214an added component of this example, apparently from the same script, is 1215the actual value of the s'd string after the substitution. 1216C<[$opt]> is a character class in perl4 and an array subscript in perl5 1217 1218 $grpc = 'a'; 1219 $opt = 'r'; 1220 $_ = 'bar'; 1221 s/^([^$grpc]*$grpc[$opt]?)/foo/; 1222 print; 1223 1224 # perl4 prints: foo 1225 # perl5 prints: foobar 1226 1227=item * C<m?x?> matches only once 1228 1229Under perl5, C<m?x?> matches only once, like C<?x?>. Under perl4, it matched 1230repeatedly, like C</x/> or C<m!x!>. 1231 1232 $test = "once"; 1233 sub match { $test =~ m?once?; } 1234 &match(); 1235 if( &match() ) { 1236 # m?x? matches more then once 1237 print "perl4\n"; 1238 } else { 1239 # m?x? matches only once 1240 print "perl5\n"; 1241 } 1242 1243 # perl4 prints: perl4 1244 # perl5 prints: perl5 1245 1246=item * Failed matches don't reset the match variables 1247 1248Unlike in Ruby, failed matches in Perl do not reset the match variables 1249($1, $2, ..., C<$`>, ...). 1250 1251=back 1252 1253=head2 Subroutine, Signal, Sorting Traps 1254 1255The general group of Perl4-to-Perl5 traps having to do with 1256Signals, Sorting, and their related subroutines, as well as 1257general subroutine traps. Includes some OS-Specific traps. 1258 1259=over 5 1260 1261=item * Barewords that used to look like strings look like subroutine calls 1262 1263Barewords that used to look like strings to Perl will now look like subroutine 1264calls if a subroutine by that name is defined before the compiler sees them. 1265 1266 sub SeeYa { warn"Hasta la vista, baby!" } 1267 $SIG{'TERM'} = SeeYa; 1268 print "SIGTERM is now $SIG{'TERM'}\n"; 1269 1270 # perl4 prints: SIGTERM is now main'SeeYa 1271 # perl5 prints: SIGTERM is now main::1 (and warns "Hasta la vista, baby!") 1272 1273Use B<-w> to catch this one 1274 1275=item * Reverse is no longer allowed as the name of a sort subroutine 1276 1277reverse is no longer allowed as the name of a sort subroutine. 1278 1279 sub reverse{ print "yup "; $a <=> $b } 1280 print sort reverse (2,1,3); 1281 1282 # perl4 prints: yup yup 123 1283 # perl5 prints: 123 1284 # perl5 warns (if using -w): Ambiguous call resolved as CORE::reverse() 1285 1286=item * C<warn()> won't let you specify a filehandle. 1287 1288Although it _always_ printed to STDERR, warn() would let you specify a 1289filehandle in perl4. With perl5 it does not. 1290 1291 warn STDERR "Foo!"; 1292 1293 # perl4 prints: Foo! 1294 # perl5 prints: String found where operator expected 1295 1296=back 1297 1298=head2 OS Traps 1299 1300=over 5 1301 1302=item * SysV resets signal handler correctly 1303 1304Under HPUX, and some other SysV OSes, one had to reset any signal handler, 1305within the signal handler function, each time a signal was handled with 1306perl4. With perl5, the reset is now done correctly. Any code relying 1307on the handler _not_ being reset will have to be reworked. 1308 1309Since version 5.002, Perl uses sigaction() under SysV. 1310 1311 sub gotit { 1312 print "Got @_... "; 1313 } 1314 $SIG{'INT'} = 'gotit'; 1315 1316 $| = 1; 1317 $pid = fork; 1318 if ($pid) { 1319 kill('INT', $pid); 1320 sleep(1); 1321 kill('INT', $pid); 1322 } else { 1323 while (1) {sleep(10);} 1324 } 1325 1326 # perl4 (HPUX) prints: Got INT... 1327 # perl5 (HPUX) prints: Got INT... Got INT... 1328 1329=item * SysV C<seek()> appends correctly 1330 1331Under SysV OSes, C<seek()> on a file opened to append C<<< >> >>> now does 1332the right thing w.r.t. the fopen() manpage. e.g., - When a file is opened 1333for append, it is impossible to overwrite information already in 1334the file. 1335 1336 open(TEST,">>seek.test"); 1337 $start = tell TEST; 1338 foreach(1 .. 9){ 1339 print TEST "$_ "; 1340 } 1341 $end = tell TEST; 1342 seek(TEST,$start,0); 1343 print TEST "18 characters here"; 1344 1345 # perl4 (solaris) seek.test has: 18 characters here 1346 # perl5 (solaris) seek.test has: 1 2 3 4 5 6 7 8 9 18 characters here 1347 1348 1349 1350=back 1351 1352=head2 Interpolation Traps 1353 1354Perl4-to-Perl5 traps having to do with how things get interpolated 1355within certain expressions, statements, contexts, or whatever. 1356 1357=over 5 1358 1359=item * C<@> always interpolates an array in double-quotish strings 1360 1361@ now always interpolates an array in double-quotish strings. 1362 1363 print "To: someone@somewhere.com\n"; 1364 1365 # perl4 prints: To:someone@somewhere.com 1366 # perl < 5.6.1, error : In string, @somewhere now must be written as \@somewhere 1367 # perl >= 5.6.1, warning : Possible unintended interpolation of @somewhere in string 1368 1369=item * Double-quoted strings may no longer end with an unescaped $ 1370 1371Double-quoted strings may no longer end with an unescaped $. 1372 1373 $foo = "foo$"; 1374 print "foo is $foo\n"; 1375 1376 # perl4 prints: foo is foo$ 1377 # perl5 errors: Final $ should be \$ or $name 1378 1379Note: perl5 DOES NOT error on the terminating @ in $bar 1380 1381=item * Arbitrary expressions are evaluated inside braces within double quotes 1382 1383Perl now sometimes evaluates arbitrary expressions inside braces that occur 1384within double quotes (usually when the opening brace is preceded by C<$> 1385or C<@>). 1386 1387 @www = "buz"; 1388 $foo = "foo"; 1389 $bar = "bar"; 1390 sub foo { return "bar" }; 1391 print "|@{w.w.w}|${main'foo}|"; 1392 1393 # perl4 prints: |@{w.w.w}|foo| 1394 # perl5 prints: |buz|bar| 1395 1396Note that you can C<use strict;> to ward off such trappiness under perl5. 1397 1398=item * C<$$x> now tries to dereference $x 1399 1400The construct "this is $$x" used to interpolate the pid at that point, but 1401now tries to dereference $x. C<$$> by itself still works fine, however. 1402 1403 $s = "a reference"; 1404 $x = *s; 1405 print "this is $$x\n"; 1406 1407 # perl4 prints: this is XXXx (XXX is the current pid) 1408 # perl5 prints: this is a reference 1409 1410=item * Creation of hashes on the fly with C<eval "EXPR"> requires protection 1411 1412Creation of hashes on the fly with C<eval "EXPR"> now requires either both 1413C<$>'s to be protected in the specification of the hash name, or both curlies 1414to be protected. If both curlies are protected, the result will be compatible 1415with perl4 and perl5. This is a very common practice, and should be changed 1416to use the block form of C<eval{}> if possible. 1417 1418 $hashname = "foobar"; 1419 $key = "baz"; 1420 $value = 1234; 1421 eval "\$$hashname{'$key'} = q|$value|"; 1422 (defined($foobar{'baz'})) ? (print "Yup") : (print "Nope"); 1423 1424 # perl4 prints: Yup 1425 # perl5 prints: Nope 1426 1427Changing 1428 1429 eval "\$$hashname{'$key'} = q|$value|"; 1430 1431to 1432 1433 eval "\$\$hashname{'$key'} = q|$value|"; 1434 1435causes the following result: 1436 1437 # perl4 prints: Nope 1438 # perl5 prints: Yup 1439 1440or, changing to 1441 1442 eval "\$$hashname\{'$key'\} = q|$value|"; 1443 1444causes the following result: 1445 1446 # perl4 prints: Yup 1447 # perl5 prints: Yup 1448 # and is compatible for both versions 1449 1450 1451=item * Bugs in earlier perl versions 1452 1453perl4 programs which unconsciously rely on the bugs in earlier perl versions. 1454 1455 perl -e '$bar=q/not/; print "This is $foo{$bar} perl5"' 1456 1457 # perl4 prints: This is not perl5 1458 # perl5 prints: This is perl5 1459 1460=item * Array and hash brackets during interpolation 1461 1462You also have to be careful about array and hash brackets during 1463interpolation. 1464 1465 print "$foo[" 1466 1467 perl 4 prints: [ 1468 perl 5 prints: syntax error 1469 1470 print "$foo{" 1471 1472 perl 4 prints: { 1473 perl 5 prints: syntax error 1474 1475Perl 5 is expecting to find an index or key name following the respective 1476brackets, as well as an ending bracket of the appropriate type. In order 1477to mimic the behavior of Perl 4, you must escape the bracket like so. 1478 1479 print "$foo\["; 1480 print "$foo\{"; 1481 1482=item * Interpolation of C<\$$foo{bar}> 1483 1484Similarly, watch out for: C<\$$foo{bar}> 1485 1486 $foo = "baz"; 1487 print "\$$foo{bar}\n"; 1488 1489 # perl4 prints: $baz{bar} 1490 # perl5 prints: $ 1491 1492Perl 5 is looking for C<$foo{bar}> which doesn't exist, but perl 4 is 1493happy just to expand $foo to "baz" by itself. Watch out for this 1494especially in C<eval>'s. 1495 1496=item * C<qq()> string passed to C<eval> will not find string terminator 1497 1498C<qq()> string passed to C<eval> 1499 1500 eval qq( 1501 foreach \$y (keys %\$x\) { 1502 \$count++; 1503 } 1504 ); 1505 1506 # perl4 runs this ok 1507 # perl5 prints: Can't find string terminator ")" 1508 1509=back 1510 1511=head2 DBM Traps 1512 1513General DBM traps. 1514 1515=over 5 1516 1517=item * Perl5 must have been linked with same dbm/ndbm as the default for C<dbmopen()> 1518 1519Existing dbm databases created under perl4 (or any other dbm/ndbm tool) 1520may cause the same script, run under perl5, to fail. The build of perl5 1521must have been linked with the same dbm/ndbm as the default for C<dbmopen()> 1522to function properly without C<tie>'ing to an extension dbm implementation. 1523 1524 dbmopen (%dbm, "file", undef); 1525 print "ok\n"; 1526 1527 # perl4 prints: ok 1528 # perl5 prints: ok (IFF linked with -ldbm or -lndbm) 1529 1530 1531=item * DBM exceeding limit on the key/value size will cause perl5 to exit immediately 1532 1533Existing dbm databases created under perl4 (or any other dbm/ndbm tool) 1534may cause the same script, run under perl5, to fail. The error generated 1535when exceeding the limit on the key/value size will cause perl5 to exit 1536immediately. 1537 1538 dbmopen(DB, "testdb",0600) || die "couldn't open db! $!"; 1539 $DB{'trap'} = "x" x 1024; # value too large for most dbm/ndbm 1540 print "YUP\n"; 1541 1542 # perl4 prints: 1543 dbm store returned -1, errno 28, key "trap" at - line 3. 1544 YUP 1545 1546 # perl5 prints: 1547 dbm store returned -1, errno 28, key "trap" at - line 3. 1548 1549=back 1550 1551=head2 Unclassified Traps 1552 1553Everything else. 1554 1555=over 5 1556 1557=item * C<require>/C<do> trap using returned value 1558 1559If the file doit.pl has: 1560 1561 sub foo { 1562 $rc = do "./do.pl"; 1563 return 8; 1564 } 1565 print &foo, "\n"; 1566 1567And the do.pl file has the following single line: 1568 1569 return 3; 1570 1571Running doit.pl gives the following: 1572 1573 # perl 4 prints: 3 (aborts the subroutine early) 1574 # perl 5 prints: 8 1575 1576Same behavior if you replace C<do> with C<require>. 1577 1578=item * C<split> on empty string with LIMIT specified 1579 1580 $string = ''; 1581 @list = split(/foo/, $string, 2) 1582 1583Perl4 returns a one element list containing the empty string but Perl5 1584returns an empty list. 1585 1586=back 1587 1588As always, if any of these are ever officially declared as bugs, 1589they'll be fixed and removed. 1590 1591