1PERLTRAP(1)            Perl Programmers Reference Guide            PERLTRAP(1)
2
3
4

NAME

6       perltrap - Perl traps for the unwary
7

DESCRIPTION

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