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               @a = (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.373503999999999614
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 last argument. It gives scalar or void
809            context to any preceding arguments, depending on circumstances.
810
811                @y= ('a','b','c');
812                $x = (1, 2, @y);
813                print "x = $x\n";
814
815                # Perl4 prints:  x = c   # Interpolates array @y into the list
816                # Perl5 prints:  x = 3   # Evaluates array @y in scalar context
817
818       ·    "sprintf()" prototyped as "($;@)"
819
820            "sprintf()" is prototyped as ($;@), so its first argument is given
821            scalar context. Thus, if passed an array, it will probably not do
822            what you want, unlike Perl 4:
823
824                @z = ('%s%s', 'foo', 'bar');
825                $x = sprintf(@z);
826                print $x;
827
828                # perl4 prints: foobar
829                # perl5 prints: 3
830
831            "printf()" works the same as it did in Perl 4, though:
832
833                @z = ('%s%s', 'foo', 'bar');
834                printf STDOUT (@z);
835
836                # perl4 prints: foobar
837                # perl5 prints: foobar
838
839   Precedence Traps
840       Perl4-to-Perl5 traps involving precedence order.
841
842       Perl 4 has almost the same precedence rules as Perl 5 for the operators
843       that they both have.  Perl 4 however, seems to have had some
844       inconsistencies that made the behavior differ from what was documented.
845
846       ·    LHS vs. RHS of any assignment operator
847
848            LHS vs. RHS of any assignment operator.  LHS is evaluated first in
849            perl4, second in perl5; this can affect the relationship between
850            side-effects in sub-expressions.
851
852                @arr = ( 'left', 'right' );
853                $a{shift @arr} = shift @arr;
854                print join( ' ', keys %a );
855
856                # perl4 prints: left
857                # perl5 prints: right
858
859       ·    Semantic errors introduced due to precedence
860
861            These are now semantic errors because of precedence:
862
863                @list = (1,2,3,4,5);
864                %map = ("a",1,"b",2,"c",3,"d",4);
865                $n = shift @list + 2;   # first item in list plus 2
866                print "n is $n, ";
867                $m = keys %map + 2;     # number of items in hash plus 2
868                print "m is $m\n";
869
870                # perl4 prints: n is 3, m is 6
871                # perl5 errors and fails to compile
872
873       ·    Precedence of assignment operators same as the precedence of
874            assignment
875
876            The precedence of assignment operators is now the same as the
877            precedence of assignment.  Perl 4 mistakenly gave them the
878            precedence of the associated operator.  So you now must
879            parenthesize them in expressions like
880
881                /foo/ ? ($a += 2) : ($a -= 2);
882
883            Otherwise
884
885                /foo/ ? $a += 2 : $a -= 2
886
887            would be erroneously parsed as
888
889                (/foo/ ? $a += 2 : $a) -= 2;
890
891            On the other hand,
892
893                $a += /foo/ ? 1 : 2;
894
895            now works as a C programmer would expect.
896
897       ·    "open" requires parentheses around filehandle
898
899                open FOO || die;
900
901            is now incorrect.  You need parentheses around the filehandle.
902            Otherwise, perl5 leaves the statement as its default precedence:
903
904                open(FOO || die);
905
906                # perl4 opens or dies
907                # perl5 opens FOO, dying only if 'FOO' is false, i.e. never
908
909       ·    $: precedence over $:: gone
910
911            perl4 gives the special variable, $: precedence, where perl5
912            treats $:: as main "package"
913
914                $a = "x"; print "$::a";
915
916                # perl 4 prints: -:a
917                # perl 5 prints: x
918
919       ·    Precedence of file test operators documented
920
921            perl4 had buggy precedence for the file test operators vis-a-vis
922            the assignment operators.  Thus, although the precedence table for
923            perl4 leads one to believe "-e $foo .= "q"" should parse as "((-e
924            $foo) .= "q")", it actually parses as "(-e ($foo .= "q"))".  In
925            perl5, the precedence is as documented.
926
927                -e $foo .= "q"
928
929                # perl4 prints: no output
930                # perl5 prints: Can't modify -e in concatenation
931
932       ·    "keys", "each", "values" are regular named unary operators
933
934            In perl4, keys(), each() and values() were special high-precedence
935            operators that operated on a single hash, but in perl5, they are
936            regular named unary operators.  As documented, named unary
937            operators have lower precedence than the arithmetic and
938            concatenation operators "+ - .", but the perl4 variants of these
939            operators actually bind tighter than "+ - .".  Thus, for:
940
941                %foo = 1..10;
942                print keys %foo - 1
943
944                # perl4 prints: 4
945                # perl5 prints: Type of arg 1 to keys must be hash (not subtraction)
946
947            The perl4 behavior was probably more useful, if less consistent.
948
949   General Regular Expression Traps using s///, etc.
950       All types of RE traps.
951
952       ·    "s'$lhs'$rhs'" interpolates on either side
953
954            "s'$lhs'$rhs'" now does no interpolation on either side.  It used
955            to interpolate $lhs but not $rhs.  (And still does not match a
956            literal '$' in string)
957
958                $a=1;$b=2;
959                $string = '1 2 $a $b';
960                $string =~ s'$a'$b';
961                print $string,"\n";
962
963                # perl4 prints: $b 2 $a $b
964                # perl5 prints: 1 2 $a $b
965
966       ·    "m//g" attaches its state to the searched string
967
968            "m//g" now attaches its state to the searched string rather than
969            the regular expression.  (Once the scope of a block is left for
970            the sub, the state of the searched string is lost)
971
972                $_ = "ababab";
973                while(m/ab/g){
974                    &doit("blah");
975                }
976                sub doit{local($_) = shift; print "Got $_ "}
977
978                # perl4 prints: Got blah Got blah Got blah Got blah
979                # perl5 prints: infinite loop blah...
980
981       ·    "m//o" used within an anonymous sub
982
983            Currently, if you use the "m//o" qualifier on a regular expression
984            within an anonymous sub, all closures generated from that
985            anonymous sub will use the regular expression as it was compiled
986            when it was used the very first time in any such closure.  For
987            instance, if you say
988
989                sub build_match {
990                    my($left,$right) = @_;
991                    return sub { $_[0] =~ /$left stuff $right/o; };
992                }
993                $good = build_match('foo','bar');
994                $bad = build_match('baz','blarch');
995                print $good->('foo stuff bar') ? "ok\n" : "not ok\n";
996                print $bad->('baz stuff blarch') ? "ok\n" : "not ok\n";
997                print $bad->('foo stuff bar') ? "not ok\n" : "ok\n";
998
999            For most builds of Perl5, this will print: ok not ok not ok
1000
1001            build_match() will always return a sub which matches the contents
1002            of $left and $right as they were the first time that build_match()
1003            was called, not as they are in the current call.
1004
1005       ·    $+ isn't set to whole match
1006
1007            If no parentheses are used in a match, Perl4 sets $+ to the whole
1008            match, just like $&. Perl5 does not.
1009
1010                "abcdef" =~ /b.*e/;
1011                print "\$+ = $+\n";
1012
1013                # perl4 prints: bcde
1014                # perl5 prints:
1015
1016       ·    Substitution now returns null string if it fails
1017
1018            substitution now returns the null string if it fails
1019
1020                $string = "test";
1021                $value = ($string =~ s/foo//);
1022                print $value, "\n";
1023
1024                # perl4 prints: 0
1025                # perl5 prints:
1026
1027            Also see "Numerical Traps" for another example of this new
1028            feature.
1029
1030       ·    "s`lhs`rhs`" is now a normal substitution
1031
1032            "s`lhs`rhs`" (using backticks) is now a normal substitution, with
1033            no backtick expansion
1034
1035                $string = "";
1036                $string =~ s`^`hostname`;
1037                print $string, "\n";
1038
1039                # perl4 prints: <the local hostname>
1040                # perl5 prints: hostname
1041
1042       ·    Stricter parsing of variables in regular expressions
1043
1044            Stricter parsing of variables used in regular expressions
1045
1046                s/^([^$grpc]*$grpc[$opt$plus$rep]?)//o;
1047
1048                # perl4: compiles w/o error
1049                # perl5: with Scalar found where operator expected ..., near "$opt$plus"
1050
1051            an added component of this example, apparently from the same
1052            script, is the actual value of the s'd string after the
1053            substitution.  "[$opt]" is a character class in perl4 and an array
1054            subscript in perl5
1055
1056                $grpc = 'a';
1057                $opt  = 'r';
1058                $_ = 'bar';
1059                s/^([^$grpc]*$grpc[$opt]?)/foo/;
1060                print;
1061
1062                # perl4 prints: foo
1063                # perl5 prints: foobar
1064
1065       ·    "m?x?" matches only once
1066
1067            Under perl5, "m?x?" matches only once, like "?x?". Under perl4, it
1068            matched repeatedly, like "/x/" or "m!x!".
1069
1070                $test = "once";
1071                sub match { $test =~ m?once?; }
1072                &match();
1073                if( &match() ) {
1074                    # m?x? matches more then once
1075                    print "perl4\n";
1076                } else {
1077                    # m?x? matches only once
1078                    print "perl5\n";
1079                }
1080
1081                # perl4 prints: perl4
1082                # perl5 prints: perl5
1083
1084       ·    Failed matches don't reset the match variables
1085
1086            Unlike in Ruby, failed matches in Perl do not reset the match
1087            variables ($1, $2, ..., "$`", ...).
1088
1089   Subroutine, Signal, Sorting Traps
1090       The general group of Perl4-to-Perl5 traps having to do with Signals,
1091       Sorting, and their related subroutines, as well as general subroutine
1092       traps.  Includes some OS-Specific traps.
1093
1094       ·    Barewords that used to look like strings look like subroutine
1095            calls
1096
1097            Barewords that used to look like strings to Perl will now look
1098            like subroutine calls if a subroutine by that name is defined
1099            before the compiler sees them.
1100
1101                sub SeeYa { warn"Hasta la vista, baby!" }
1102                $SIG{'TERM'} = SeeYa;
1103                print "SIGTERM is now $SIG{'TERM'}\n";
1104
1105                # perl4 prints: SIGTERM is now main'SeeYa
1106                # perl5 prints: SIGTERM is now main::1 (and warns "Hasta la vista, baby!")
1107
1108            Use -w to catch this one
1109
1110       ·    Reverse is no longer allowed as the name of a sort subroutine
1111
1112            reverse is no longer allowed as the name of a sort subroutine.
1113
1114                sub reverse{ print "yup "; $a <=> $b }
1115                print sort reverse (2,1,3);
1116
1117                # perl4 prints: yup yup 123
1118                # perl5 prints: 123
1119                # perl5 warns (if using -w): Ambiguous call resolved as CORE::reverse()
1120
1121       ·    "warn()" won't let you specify a filehandle.
1122
1123            Although it _always_ printed to STDERR, warn() would let you
1124            specify a filehandle in perl4.  With perl5 it does not.
1125
1126                warn STDERR "Foo!";
1127
1128                # perl4 prints: Foo!
1129                # perl5 prints: String found where operator expected
1130
1131   OS Traps
1132       ·    SysV resets signal handler correctly
1133
1134            Under HPUX, and some other SysV OSes, one had to reset any signal
1135            handler, within  the signal handler function, each time a signal
1136            was handled with perl4.  With perl5, the reset is now done
1137            correctly.  Any code relying on the handler _not_ being reset will
1138            have to be reworked.
1139
1140            Since version 5.002, Perl uses sigaction() under SysV.
1141
1142                sub gotit {
1143                    print "Got @_... ";
1144                }
1145                $SIG{'INT'} = 'gotit';
1146
1147                $| = 1;
1148                $pid = fork;
1149                if ($pid) {
1150                    kill('INT', $pid);
1151                    sleep(1);
1152                    kill('INT', $pid);
1153                } else {
1154                    while (1) {sleep(10);}
1155                }
1156
1157                # perl4 (HPUX) prints: Got INT...
1158                # perl5 (HPUX) prints: Got INT... Got INT...
1159
1160       ·    SysV "seek()" appends correctly
1161
1162            Under SysV OSes, "seek()" on a file opened to append ">>" now does
1163            the right thing w.r.t. the fopen() manpage. e.g., - When a file is
1164            opened for append,  it  is  impossible to overwrite information
1165            already in the file.
1166
1167                open(TEST,">>seek.test");
1168                $start = tell TEST;
1169                foreach(1 .. 9){
1170                    print TEST "$_ ";
1171                }
1172                $end = tell TEST;
1173                seek(TEST,$start,0);
1174                print TEST "18 characters here";
1175
1176                # perl4 (solaris) seek.test has: 18 characters here
1177                # perl5 (solaris) seek.test has: 1 2 3 4 5 6 7 8 9 18 characters here
1178
1179   Interpolation Traps
1180       Perl4-to-Perl5 traps having to do with how things get interpolated
1181       within certain expressions, statements, contexts, or whatever.
1182
1183       ·    "@" always interpolates an array in double-quotish strings
1184
1185            @ now always interpolates an array in double-quotish strings.
1186
1187                print "To: someone@somewhere.com\n";
1188
1189                # perl4 prints: To:someone@somewhere.com
1190                # perl < 5.6.1, error : In string, @somewhere now must be written as \@somewhere
1191                # perl >= 5.6.1, warning : Possible unintended interpolation of @somewhere in string
1192
1193       ·    Double-quoted strings may no longer end with an unescaped $
1194
1195            Double-quoted strings may no longer end with an unescaped $.
1196
1197                $foo = "foo$";
1198                print "foo is $foo\n";
1199
1200                # perl4 prints: foo is foo$
1201                # perl5 errors: Final $ should be \$ or $name
1202
1203            Note: perl5 DOES NOT error on the terminating @ in $bar
1204
1205       ·    Arbitrary expressions are evaluated inside braces within double
1206            quotes
1207
1208            Perl now sometimes evaluates arbitrary expressions inside braces
1209            that occur within double quotes (usually when the opening brace is
1210            preceded by "$" or "@").
1211
1212                @www = "buz";
1213                $foo = "foo";
1214                $bar = "bar";
1215                sub foo { return "bar" };
1216                print "|@{w.w.w}|${main'foo}|";
1217
1218                # perl4 prints: |@{w.w.w}|foo|
1219                # perl5 prints: |buz|bar|
1220
1221            Note that you can "use strict;" to ward off such trappiness under
1222            perl5.
1223
1224       ·    $$x now tries to dereference $x
1225
1226            The construct "this is $$x" used to interpolate the pid at that
1227            point, but now tries to dereference $x.  $$ by itself still works
1228            fine, however.
1229
1230                $s = "a reference";
1231                $x = *s;
1232                print "this is $$x\n";
1233
1234                # perl4 prints: this is XXXx   (XXX is the current pid)
1235                # perl5 prints: this is a reference
1236
1237       ·    Creation of hashes on the fly with "eval "EXPR"" requires
1238            protection
1239
1240            Creation of hashes on the fly with "eval "EXPR"" now requires
1241            either both "$"'s to be protected in the specification of the hash
1242            name, or both curlies to be protected.  If both curlies are
1243            protected, the result will be compatible with perl4 and perl5.
1244            This is a very common practice, and should be changed to use the
1245            block form of "eval{}"  if possible.
1246
1247                $hashname = "foobar";
1248                $key = "baz";
1249                $value = 1234;
1250                eval "\$$hashname{'$key'} = q|$value|";
1251                (defined($foobar{'baz'})) ?  (print "Yup") : (print "Nope");
1252
1253                # perl4 prints: Yup
1254                # perl5 prints: Nope
1255
1256            Changing
1257
1258                eval "\$$hashname{'$key'} = q|$value|";
1259
1260            to
1261
1262                eval "\$\$hashname{'$key'} = q|$value|";
1263
1264            causes the following result:
1265
1266                # perl4 prints: Nope
1267                # perl5 prints: Yup
1268
1269            or, changing to
1270
1271                eval "\$$hashname\{'$key'\} = q|$value|";
1272
1273            causes the following result:
1274
1275                # perl4 prints: Yup
1276                # perl5 prints: Yup
1277                # and is compatible for both versions
1278
1279       ·    Bugs in earlier perl versions
1280
1281            perl4 programs which unconsciously rely on the bugs in earlier
1282            perl versions.
1283
1284                perl -e '$bar=q/not/; print "This is $foo{$bar} perl5"'
1285
1286                # perl4 prints: This is not perl5
1287                # perl5 prints: This is perl5
1288
1289       ·    Array and hash brackets during interpolation
1290
1291            You also have to be careful about array and hash brackets during
1292            interpolation.
1293
1294                print "$foo["
1295
1296                perl 4 prints: [
1297                perl 5 prints: syntax error
1298
1299                print "$foo{"
1300
1301                perl 4 prints: {
1302                perl 5 prints: syntax error
1303
1304            Perl 5 is expecting to find an index or key name following the
1305            respective brackets, as well as an ending bracket of the
1306            appropriate type.  In order to mimic the behavior of Perl 4, you
1307            must escape the bracket like so.
1308
1309                print "$foo\[";
1310                print "$foo\{";
1311
1312       ·    Interpolation of "\$$foo{bar}"
1313
1314            Similarly, watch out for: "\$$foo{bar}"
1315
1316                $foo = "baz";
1317                print "\$$foo{bar}\n";
1318
1319                # perl4 prints: $baz{bar}
1320                # perl5 prints: $
1321
1322            Perl 5 is looking for $foo{bar} which doesn't exist, but perl 4 is
1323            happy just to expand $foo to "baz" by itself.  Watch out for this
1324            especially in "eval"'s.
1325
1326       ·    "qq()" string passed to "eval" will not find string terminator
1327
1328            "qq()" string passed to "eval"
1329
1330                eval qq(
1331                    foreach \$y (keys %\$x\) {
1332                        \$count++;
1333                    }
1334                );
1335
1336                # perl4 runs this ok
1337                # perl5 prints: Can't find string terminator ")"
1338
1339   DBM Traps
1340       General DBM traps.
1341
1342       ·    Perl5 must have been linked with same dbm/ndbm as the default for
1343            "dbmopen()"
1344
1345            Existing dbm databases created under perl4 (or any other dbm/ndbm
1346            tool) may cause the same script, run under perl5, to fail.  The
1347            build of perl5 must have been linked with the same dbm/ndbm as the
1348            default for "dbmopen()" to function properly without "tie"'ing to
1349            an extension dbm implementation.
1350
1351                dbmopen (%dbm, "file", undef);
1352                print "ok\n";
1353
1354                # perl4 prints: ok
1355                # perl5 prints: ok (IFF linked with -ldbm or -lndbm)
1356
1357       ·    DBM exceeding limit on the key/value size will cause perl5 to exit
1358            immediately
1359
1360            Existing dbm databases created under perl4 (or any other dbm/ndbm
1361            tool) may cause the same script, run under perl5, to fail.  The
1362            error generated when exceeding the limit on the key/value size
1363            will cause perl5 to exit immediately.
1364
1365                dbmopen(DB, "testdb",0600) || die "couldn't open db! $!";
1366                $DB{'trap'} = "x" x 1024;  # value too large for most dbm/ndbm
1367                print "YUP\n";
1368
1369                # perl4 prints:
1370                dbm store returned -1, errno 28, key "trap" at - line 3.
1371                YUP
1372
1373                # perl5 prints:
1374                dbm store returned -1, errno 28, key "trap" at - line 3.
1375
1376   Unclassified Traps
1377       Everything else.
1378
1379       ·    "require"/"do" trap using returned value
1380
1381            If the file doit.pl has:
1382
1383                sub foo {
1384                    $rc = do "./do.pl";
1385                    return 8;
1386                }
1387                print &foo, "\n";
1388
1389            And the do.pl file has the following single line:
1390
1391                return 3;
1392
1393            Running doit.pl gives the following:
1394
1395                # perl 4 prints: 3 (aborts the subroutine early)
1396                # perl 5 prints: 8
1397
1398            Same behavior if you replace "do" with "require".
1399
1400       ·    "split" on empty string with LIMIT specified
1401
1402                $string = '';
1403                @list = split(/foo/, $string, 2)
1404
1405            Perl4 returns a one element list containing the empty string but
1406            Perl5 returns an empty list.
1407
1408       As always, if any of these are ever officially declared as bugs,
1409       they'll be fixed and removed.
1410
1411
1412
1413perl v5.16.3                      2013-03-04                       PERLTRAP(1)
Impressum