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