Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1505 lines
35 KiB

  1. =head1 NAME
  2. perltrap - Perl traps for the unwary
  3. =head1 DESCRIPTION
  4. The biggest trap of all is forgetting to use the B<-w> switch; see
  5. L<perlrun>. The second biggest trap is not making your entire program
  6. runnable under C<use strict>. The third biggest trap is not reading
  7. the list of changes in this version of Perl; see L<perldelta>.
  8. =head2 Awk Traps
  9. Accustomed B<awk> users should take special note of the following:
  10. =over 4
  11. =item *
  12. The English module, loaded via
  13. use English;
  14. allows you to refer to special variables (like C<$/>) with names (like
  15. C<$RS>), as though they were in B<awk>; see L<perlvar> for details.
  16. =item *
  17. Semicolons are required after all simple statements in Perl (except
  18. at the end of a block). Newline is not a statement delimiter.
  19. =item *
  20. Curly brackets are required on C<if>s and C<while>s.
  21. =item *
  22. Variables begin with "$", "@" or "%" in Perl.
  23. =item *
  24. Arrays index from 0. Likewise string positions in substr() and
  25. index().
  26. =item *
  27. You have to decide whether your array has numeric or string indices.
  28. =item *
  29. Hash values do not spring into existence upon mere reference.
  30. =item *
  31. You have to decide whether you want to use string or numeric
  32. comparisons.
  33. =item *
  34. Reading an input line does not split it for you. You get to split it
  35. to an array yourself. And the split() operator has different
  36. arguments than B<awk>'s.
  37. =item *
  38. The current input line is normally in $_, not $0. It generally does
  39. not have the newline stripped. ($0 is the name of the program
  40. executed.) See L<perlvar>.
  41. =item *
  42. $E<lt>I<digit>E<gt> does not refer to fields--it refers to substrings matched
  43. by the last match pattern.
  44. =item *
  45. The print() statement does not add field and record separators unless
  46. you set C<$,> and C<$\>. You can set $OFS and $ORS if you're using
  47. the English module.
  48. =item *
  49. You must open your files before you print to them.
  50. =item *
  51. The range operator is "..", not comma. The comma operator works as in
  52. C.
  53. =item *
  54. The match operator is "=~", not "~". ("~" is the one's complement
  55. operator, as in C.)
  56. =item *
  57. The exponentiation operator is "**", not "^". "^" is the XOR
  58. operator, as in C. (You know, one could get the feeling that B<awk> is
  59. basically incompatible with C.)
  60. =item *
  61. The concatenation operator is ".", not the null string. (Using the
  62. null string would render C</pat/ /pat/> unparsable, because the third slash
  63. would be interpreted as a division operator--the tokenizer is in fact
  64. slightly context sensitive for operators like "/", "?", and "E<gt>".
  65. And in fact, "." itself can be the beginning of a number.)
  66. =item *
  67. The C<next>, C<exit>, and C<continue> keywords work differently.
  68. =item *
  69. The following variables work differently:
  70. Awk Perl
  71. ARGC $#ARGV or scalar @ARGV
  72. ARGV[0] $0
  73. FILENAME $ARGV
  74. FNR $. - something
  75. FS (whatever you like)
  76. NF $#Fld, or some such
  77. NR $.
  78. OFMT $#
  79. OFS $,
  80. ORS $\
  81. RLENGTH length($&)
  82. RS $/
  83. RSTART length($`)
  84. SUBSEP $;
  85. =item *
  86. You cannot set $RS to a pattern, only a string.
  87. =item *
  88. When in doubt, run the B<awk> construct through B<a2p> and see what it
  89. gives you.
  90. =back
  91. =head2 C Traps
  92. Cerebral C programmers should take note of the following:
  93. =over 4
  94. =item *
  95. Curly brackets are required on C<if>'s and C<while>'s.
  96. =item *
  97. You must use C<elsif> rather than C<else if>.
  98. =item *
  99. The C<break> and C<continue> keywords from C become in
  100. Perl C<last> and C<next>, respectively.
  101. Unlike in C, these do I<NOT> work within a C<do { } while> construct.
  102. =item *
  103. There's no switch statement. (But it's easy to build one on the fly.)
  104. =item *
  105. Variables begin with "$", "@" or "%" in Perl.
  106. =item *
  107. C<printf()> does not implement the "*" format for interpolating
  108. field widths, but it's trivial to use interpolation of double-quoted
  109. strings to achieve the same effect.
  110. =item *
  111. Comments begin with "#", not "/*".
  112. =item *
  113. You can't take the address of anything, although a similar operator
  114. in Perl is the backslash, which creates a reference.
  115. =item *
  116. C<ARGV> must be capitalized. C<$ARGV[0]> is C's C<argv[1]>, and C<argv[0]>
  117. ends up in C<$0>.
  118. =item *
  119. System calls such as link(), unlink(), rename(), etc. return nonzero for
  120. success, not 0.
  121. =item *
  122. Signal handlers deal with signal names, not numbers. Use C<kill -l>
  123. to find their names on your system.
  124. =back
  125. =head2 Sed Traps
  126. Seasoned B<sed> programmers should take note of the following:
  127. =over 4
  128. =item *
  129. Backreferences in substitutions use "$" rather than "\".
  130. =item *
  131. The pattern matching metacharacters "(", ")", and "|" do not have backslashes
  132. in front.
  133. =item *
  134. The range operator is C<...>, rather than comma.
  135. =back
  136. =head2 Shell Traps
  137. Sharp shell programmers should take note of the following:
  138. =over 4
  139. =item *
  140. The backtick operator does variable interpolation without regard to
  141. the presence of single quotes in the command.
  142. =item *
  143. The backtick operator does no translation of the return value, unlike B<csh>.
  144. =item *
  145. Shells (especially B<csh>) do several levels of substitution on each
  146. command line. Perl does substitution in only certain constructs
  147. such as double quotes, backticks, angle brackets, and search patterns.
  148. =item *
  149. Shells interpret scripts a little bit at a time. Perl compiles the
  150. entire program before executing it (except for C<BEGIN> blocks, which
  151. execute at compile time).
  152. =item *
  153. The arguments are available via @ARGV, not $1, $2, etc.
  154. =item *
  155. The environment is not automatically made available as separate scalar
  156. variables.
  157. =back
  158. =head2 Perl Traps
  159. Practicing Perl Programmers should take note of the following:
  160. =over 4
  161. =item *
  162. Remember that many operations behave differently in a list
  163. context than they do in a scalar one. See L<perldata> for details.
  164. =item *
  165. Avoid barewords if you can, especially all lowercase ones.
  166. You can't tell by just looking at it whether a bareword is
  167. a function or a string. By using quotes on strings and
  168. parentheses on function calls, you won't ever get them confused.
  169. =item *
  170. You cannot discern from mere inspection which builtins
  171. are unary operators (like chop() and chdir())
  172. and which are list operators (like print() and unlink()).
  173. (User-defined subroutines can be B<only> list operators, never
  174. unary ones.) See L<perlop>.
  175. =item *
  176. People have a hard time remembering that some functions
  177. default to $_, or @ARGV, or whatever, but that others which
  178. you might expect to do not.
  179. =item *
  180. The E<lt>FHE<gt> construct is not the name of the filehandle, it is a readline
  181. operation on that handle. The data read is assigned to $_ only if the
  182. file read is the sole condition in a while loop:
  183. while (<FH>) { }
  184. while (defined($_ = <FH>)) { }..
  185. <FH>; # data discarded!
  186. =item *
  187. Remember not to use "C<=>" when you need "C<=~>";
  188. these two constructs are quite different:
  189. $x = /foo/;
  190. $x =~ /foo/;
  191. =item *
  192. The C<do {}> construct isn't a real loop that you can use
  193. loop control on.
  194. =item *
  195. Use C<my()> for local variables whenever you can get away with
  196. it (but see L<perlform> for where you can't).
  197. Using C<local()> actually gives a local value to a global
  198. variable, which leaves you open to unforeseen side-effects
  199. of dynamic scoping.
  200. =item *
  201. If you localize an exported variable in a module, its exported value will
  202. not change. The local name becomes an alias to a new value but the
  203. external name is still an alias for the original.
  204. =back
  205. =head2 Perl4 to Perl5 Traps
  206. Practicing Perl4 Programmers should take note of the following
  207. Perl4-to-Perl5 specific traps.
  208. They're crudely ordered according to the following list:
  209. =over 4
  210. =item Discontinuance, Deprecation, and BugFix traps
  211. Anything that's been fixed as a perl4 bug, removed as a perl4 feature
  212. or deprecated as a perl4 feature with the intent to encourage usage of
  213. some other perl5 feature.
  214. =item Parsing Traps
  215. Traps that appear to stem from the new parser.
  216. =item Numerical Traps
  217. Traps having to do with numerical or mathematical operators.
  218. =item General data type traps
  219. Traps involving perl standard data types.
  220. =item Context Traps - scalar, list contexts
  221. Traps related to context within lists, scalar statements/declarations.
  222. =item Precedence Traps
  223. Traps related to the precedence of parsing, evaluation, and execution of
  224. code.
  225. =item General Regular Expression Traps using s///, etc.
  226. Traps related to the use of pattern matching.
  227. =item Subroutine, Signal, Sorting Traps
  228. Traps related to the use of signals and signal handlers, general subroutines,
  229. and sorting, along with sorting subroutines.
  230. =item OS Traps
  231. OS-specific traps.
  232. =item DBM Traps
  233. Traps specific to the use of C<dbmopen()>, and specific dbm implementations.
  234. =item Unclassified Traps
  235. Everything else.
  236. =back
  237. If you find an example of a conversion trap that is not listed here,
  238. please submit it to Bill Middleton <F<[email protected]>> for inclusion.
  239. Also note that at least some of these can be caught with B<-w>.
  240. =head2 Discontinuance, Deprecation, and BugFix traps
  241. Anything that has been discontinued, deprecated, or fixed as
  242. a bug from perl4.
  243. =over 4
  244. =item * Discontinuance
  245. Symbols starting with "_" are no longer forced into package main, except
  246. for C<$_> itself (and C<@_>, etc.).
  247. package test;
  248. $_legacy = 1;
  249. package main;
  250. print "\$_legacy is ",$_legacy,"\n";
  251. # perl4 prints: $_legacy is 1
  252. # perl5 prints: $_legacy is
  253. =item * Deprecation
  254. Double-colon is now a valid package separator in a variable name. Thus these
  255. behave differently in perl4 vs. perl5, because the packages don't exist.
  256. $a=1;$b=2;$c=3;$var=4;
  257. print "$a::$b::$c ";
  258. print "$var::abc::xyz\n";
  259. # perl4 prints: 1::2::3 4::abc::xyz
  260. # perl5 prints: 3
  261. Given that C<::> is now the preferred package delimiter, it is debatable
  262. whether this should be classed as a bug or not.
  263. (The older package delimiter, ' ,is used here)
  264. $x = 10 ;
  265. print "x=${'x}\n" ;
  266. # perl4 prints: x=10
  267. # perl5 prints: Can't find string terminator "'" anywhere before EOF
  268. You can avoid this problem, and remain compatible with perl4, if you
  269. always explicitly include the package name:
  270. $x = 10 ;
  271. print "x=${main'x}\n" ;
  272. Also see precedence traps, for parsing C<$:>.
  273. =item * BugFix
  274. The second and third arguments of C<splice()> are now evaluated in scalar
  275. context (as the Camel says) rather than list context.
  276. sub sub1{return(0,2) } # return a 2-element list
  277. sub sub2{ return(1,2,3)} # return a 3-element list
  278. @a1 = ("a","b","c","d","e");
  279. @a2 = splice(@a1,&sub1,&sub2);
  280. print join(' ',@a2),"\n";
  281. # perl4 prints: a b
  282. # perl5 prints: c d e
  283. =item * Discontinuance
  284. You can't do a C<goto> into a block that is optimized away. Darn.
  285. goto marker1;
  286. for(1){
  287. marker1:
  288. print "Here I is!\n";
  289. }
  290. # perl4 prints: Here I is!
  291. # perl5 dumps core (SEGV)
  292. =item * Discontinuance
  293. It is no longer syntactically legal to use whitespace as the name
  294. of a variable, or as a delimiter for any kind of quote construct.
  295. Double darn.
  296. $a = ("foo bar");
  297. $b = q baz ;
  298. print "a is $a, b is $b\n";
  299. # perl4 prints: a is foo bar, b is baz
  300. # perl5 errors: Bareword found where operator expected
  301. =item * Discontinuance
  302. The archaic while/if BLOCK BLOCK syntax is no longer supported.
  303. if { 1 } {
  304. print "True!";
  305. }
  306. else {
  307. print "False!";
  308. }
  309. # perl4 prints: True!
  310. # perl5 errors: syntax error at test.pl line 1, near "if {"
  311. =item * BugFix
  312. The C<**> operator now binds more tightly than unary minus.
  313. It was documented to work this way before, but didn't.
  314. print -4**2,"\n";
  315. # perl4 prints: 16
  316. # perl5 prints: -16
  317. =item * Discontinuance
  318. The meaning of C<foreach{}> has changed slightly when it is iterating over a
  319. list which is not an array. This used to assign the list to a
  320. temporary array, but no longer does so (for efficiency). This means
  321. that you'll now be iterating over the actual values, not over copies of
  322. the values. Modifications to the loop variable can change the original
  323. values.
  324. @list = ('ab','abc','bcd','def');
  325. foreach $var (grep(/ab/,@list)){
  326. $var = 1;
  327. }
  328. print (join(':',@list));
  329. # perl4 prints: ab:abc:bcd:def
  330. # perl5 prints: 1:1:bcd:def
  331. To retain Perl4 semantics you need to assign your list
  332. explicitly to a temporary array and then iterate over that. For
  333. example, you might need to change
  334. foreach $var (grep(/ab/,@list)){
  335. to
  336. foreach $var (@tmp = grep(/ab/,@list)){
  337. Otherwise changing $var will clobber the values of @list. (This most often
  338. happens when you use C<$_> for the loop variable, and call subroutines in
  339. the loop that don't properly localize C<$_>.)
  340. =item * Discontinuance
  341. C<split> with no arguments now behaves like C<split ' '> (which doesn't
  342. return an initial null field if $_ starts with whitespace), it used to
  343. behave like C<split /\s+/> (which does).
  344. $_ = ' hi mom';
  345. print join(':', split);
  346. # perl4 prints: :hi:mom
  347. # perl5 prints: hi:mom
  348. =item * BugFix
  349. Perl 4 would ignore any text which was attached to an B<-e> switch,
  350. always taking the code snippet from the following arg. Additionally, it
  351. would silently accept an B<-e> switch without a following arg. Both of
  352. these behaviors have been fixed.
  353. perl -e'print "attached to -e"' 'print "separate arg"'
  354. # perl4 prints: separate arg
  355. # perl5 prints: attached to -e
  356. perl -e
  357. # perl4 prints:
  358. # perl5 dies: No code specified for -e.
  359. =item * Discontinuance
  360. In Perl 4 the return value of C<push> was undocumented, but it was
  361. actually the last value being pushed onto the target list. In Perl 5
  362. the return value of C<push> is documented, but has changed, it is the
  363. number of elements in the resulting list.
  364. @x = ('existing');
  365. print push(@x, 'first new', 'second new');
  366. # perl4 prints: second new
  367. # perl5 prints: 3
  368. =item * Discontinuance
  369. In Perl 4 (and versions of Perl 5 before 5.004), C<'\r'> characters in
  370. Perl code were silently allowed, although they could cause (mysterious!)
  371. failures in certain constructs, particularly here documents. Now,
  372. C<'\r'> characters cause an immediate fatal error. (Note: In this
  373. example, the notation B<\015> represents the incorrect line
  374. ending. Depending upon your text viewer, it will look different.)
  375. print "foo";\015
  376. print "bar";
  377. # perl4 prints: foobar
  378. # perl5.003 prints: foobar
  379. # perl5.004 dies: Illegal character \015 (carriage return)
  380. See L<perldiag> for full details.
  381. =item * Deprecation
  382. Some error messages will be different.
  383. =item * Discontinuance
  384. Some bugs may have been inadvertently removed. :-)
  385. =back
  386. =head2 Parsing Traps
  387. Perl4-to-Perl5 traps from having to do with parsing.
  388. =over 4
  389. =item * Parsing
  390. Note the space between . and =
  391. $string . = "more string";
  392. print $string;
  393. # perl4 prints: more string
  394. # perl5 prints: syntax error at - line 1, near ". ="
  395. =item * Parsing
  396. Better parsing in perl 5
  397. sub foo {}
  398. &foo
  399. print("hello, world\n");
  400. # perl4 prints: hello, world
  401. # perl5 prints: syntax error
  402. =item * Parsing
  403. "if it looks like a function, it is a function" rule.
  404. print
  405. ($foo == 1) ? "is one\n" : "is zero\n";
  406. # perl4 prints: is zero
  407. # perl5 warns: "Useless use of a constant in void context" if using -w
  408. =item * Parsing
  409. String interpolation of the C<$#array> construct differs when braces
  410. are to used around the name.
  411. @ = (1..3);
  412. print "${#a}";
  413. # perl4 prints: 2
  414. # perl5 fails with syntax error
  415. @ = (1..3);
  416. print "$#{a}";
  417. # perl4 prints: {a}
  418. # perl5 prints: 2
  419. =back
  420. =head2 Numerical Traps
  421. Perl4-to-Perl5 traps having to do with numerical operators,
  422. operands, or output from same.
  423. =over 5
  424. =item * Numerical
  425. Formatted output and significant digits
  426. print 7.373504 - 0, "\n";
  427. printf "%20.18f\n", 7.373504 - 0;
  428. # Perl4 prints:
  429. 7.375039999999996141
  430. 7.37503999999999614
  431. # Perl5 prints:
  432. 7.373504
  433. 7.37503999999999614
  434. =item * Numerical
  435. This specific item has been deleted. It demonstrated how the auto-increment
  436. operator would not catch when a number went over the signed int limit. Fixed
  437. in version 5.003_04. But always be wary when using large integers.
  438. If in doubt:
  439. use Math::BigInt;
  440. =item * Numerical
  441. Assignment of return values from numeric equality tests
  442. does not work in perl5 when the test evaluates to false (0).
  443. Logical tests now return an null, instead of 0
  444. $p = ($test == 1);
  445. print $p,"\n";
  446. # perl4 prints: 0
  447. # perl5 prints:
  448. Also see L<"General Regular Expression Traps using s///, etc.">
  449. for another example of this new feature...
  450. =back
  451. =head2 General data type traps
  452. Perl4-to-Perl5 traps involving most data-types, and their usage
  453. within certain expressions and/or context.
  454. =over 5
  455. =item * (Arrays)
  456. Negative array subscripts now count from the end of the array.
  457. @a = (1, 2, 3, 4, 5);
  458. print "The third element of the array is $a[3] also expressed as $a[-2] \n";
  459. # perl4 prints: The third element of the array is 4 also expressed as
  460. # perl5 prints: The third element of the array is 4 also expressed as 4
  461. =item * (Arrays)
  462. Setting C<$#array> lower now discards array elements, and makes them
  463. impossible to recover.
  464. @a = (a,b,c,d,e);
  465. print "Before: ",join('',@a);
  466. $#a =1;
  467. print ", After: ",join('',@a);
  468. $#a =3;
  469. print ", Recovered: ",join('',@a),"\n";
  470. # perl4 prints: Before: abcde, After: ab, Recovered: abcd
  471. # perl5 prints: Before: abcde, After: ab, Recovered: ab
  472. =item * (Hashes)
  473. Hashes get defined before use
  474. local($s,@a,%h);
  475. die "scalar \$s defined" if defined($s);
  476. die "array \@a defined" if defined(@a);
  477. die "hash \%h defined" if defined(%h);
  478. # perl4 prints:
  479. # perl5 dies: hash %h defined
  480. =item * (Globs)
  481. glob assignment from variable to variable will fail if the assigned
  482. variable is localized subsequent to the assignment
  483. @a = ("This is Perl 4");
  484. *b = *a;
  485. local(@a);
  486. print @b,"\n";
  487. # perl4 prints: This is Perl 4
  488. # perl5 prints:
  489. =item * (Globs)
  490. Assigning C<undef> to a glob has no effect in Perl 5. In Perl 4
  491. it undefines the associated scalar (but may have other side effects
  492. including SEGVs).
  493. =item * (Scalar String)
  494. Changes in unary negation (of strings)
  495. This change effects both the return value and what it
  496. does to auto(magic)increment.
  497. $x = "aaa";
  498. print ++$x," : ";
  499. print -$x," : ";
  500. print ++$x,"\n";
  501. # perl4 prints: aab : -0 : 1
  502. # perl5 prints: aab : -aab : aac
  503. =item * (Constants)
  504. perl 4 lets you modify constants:
  505. $foo = "x";
  506. &mod($foo);
  507. for ($x = 0; $x < 3; $x++) {
  508. &mod("a");
  509. }
  510. sub mod {
  511. print "before: $_[0]";
  512. $_[0] = "m";
  513. print " after: $_[0]\n";
  514. }
  515. # perl4:
  516. # before: x after: m
  517. # before: a after: m
  518. # before: m after: m
  519. # before: m after: m
  520. # Perl5:
  521. # before: x after: m
  522. # Modification of a read-only value attempted at foo.pl line 12.
  523. # before: a
  524. =item * (Scalars)
  525. The behavior is slightly different for:
  526. print "$x", defined $x
  527. # perl 4: 1
  528. # perl 5: <no output, $x is not called into existence>
  529. =item * (Variable Suicide)
  530. Variable suicide behavior is more consistent under Perl 5.
  531. Perl5 exhibits the same behavior for hashes and scalars,
  532. that perl4 exhibits for only scalars.
  533. $aGlobal{ "aKey" } = "global value";
  534. print "MAIN:", $aGlobal{"aKey"}, "\n";
  535. $GlobalLevel = 0;
  536. &test( *aGlobal );
  537. sub test {
  538. local( *theArgument ) = @_;
  539. local( %aNewLocal ); # perl 4 != 5.001l,m
  540. $aNewLocal{"aKey"} = "this should never appear";
  541. print "SUB: ", $theArgument{"aKey"}, "\n";
  542. $aNewLocal{"aKey"} = "level $GlobalLevel"; # what should print
  543. $GlobalLevel++;
  544. if( $GlobalLevel<4 ) {
  545. &test( *aNewLocal );
  546. }
  547. }
  548. # Perl4:
  549. # MAIN:global value
  550. # SUB: global value
  551. # SUB: level 0
  552. # SUB: level 1
  553. # SUB: level 2
  554. # Perl5:
  555. # MAIN:global value
  556. # SUB: global value
  557. # SUB: this should never appear
  558. # SUB: this should never appear
  559. # SUB: this should never appear
  560. =back
  561. =head2 Context Traps - scalar, list contexts
  562. =over 5
  563. =item * (list context)
  564. The elements of argument lists for formats are now evaluated in list
  565. context. This means you can interpolate list values now.
  566. @fmt = ("foo","bar","baz");
  567. format STDOUT=
  568. @<<<<< @||||| @>>>>>
  569. @fmt;
  570. .
  571. write;
  572. # perl4 errors: Please use commas to separate fields in file
  573. # perl5 prints: foo bar baz
  574. =item * (scalar context)
  575. The C<caller()> function now returns a false value in a scalar context
  576. if there is no caller. This lets library files determine if they're
  577. being required.
  578. caller() ? (print "You rang?\n") : (print "Got a 0\n");
  579. # perl4 errors: There is no caller
  580. # perl5 prints: Got a 0
  581. =item * (scalar context)
  582. The comma operator in a scalar context is now guaranteed to give a
  583. scalar context to its arguments.
  584. @y= ('a','b','c');
  585. $x = (1, 2, @y);
  586. print "x = $x\n";
  587. # Perl4 prints: x = c # Thinks list context interpolates list
  588. # Perl5 prints: x = 3 # Knows scalar uses length of list
  589. =item * (list, builtin)
  590. C<sprintf()> funkiness (array argument converted to scalar array count)
  591. This test could be added to t/op/sprintf.t
  592. @z = ('%s%s', 'foo', 'bar');
  593. $x = sprintf(@z);
  594. if ($x eq 'foobar') {print "ok 2\n";} else {print "not ok 2 '$x'\n";}
  595. # perl4 prints: ok 2
  596. # perl5 prints: not ok 2
  597. C<printf()> works fine, though:
  598. printf STDOUT (@z);
  599. print "\n";
  600. # perl4 prints: foobar
  601. # perl5 prints: foobar
  602. Probably a bug.
  603. =back
  604. =head2 Precedence Traps
  605. Perl4-to-Perl5 traps involving precedence order.
  606. Perl 4 has almost the same precedence rules as Perl 5 for the operators
  607. that they both have. Perl 4 however, seems to have had some
  608. inconsistencies that made the behavior differ from what was documented.
  609. =over 5
  610. =item * Precedence
  611. LHS vs. RHS of any assignment operator. LHS is evaluated first
  612. in perl4, second in perl5; this can affect the relationship
  613. between side-effects in sub-expressions.
  614. @arr = ( 'left', 'right' );
  615. $a{shift @arr} = shift @arr;
  616. print join( ' ', keys %a );
  617. # perl4 prints: left
  618. # perl5 prints: right
  619. =item * Precedence
  620. These are now semantic errors because of precedence:
  621. @list = (1,2,3,4,5);
  622. %map = ("a",1,"b",2,"c",3,"d",4);
  623. $n = shift @list + 2; # first item in list plus 2
  624. print "n is $n, ";
  625. $m = keys %map + 2; # number of items in hash plus 2
  626. print "m is $m\n";
  627. # perl4 prints: n is 3, m is 6
  628. # perl5 errors and fails to compile
  629. =item * Precedence
  630. The precedence of assignment operators is now the same as the precedence
  631. of assignment. Perl 4 mistakenly gave them the precedence of the associated
  632. operator. So you now must parenthesize them in expressions like
  633. /foo/ ? ($a += 2) : ($a -= 2);
  634. Otherwise
  635. /foo/ ? $a += 2 : $a -= 2
  636. would be erroneously parsed as
  637. (/foo/ ? $a += 2 : $a) -= 2;
  638. On the other hand,
  639. $a += /foo/ ? 1 : 2;
  640. now works as a C programmer would expect.
  641. =item * Precedence
  642. open FOO || die;
  643. is now incorrect. You need parentheses around the filehandle.
  644. Otherwise, perl5 leaves the statement as its default precedence:
  645. open(FOO || die);
  646. # perl4 opens or dies
  647. # perl5 errors: Precedence problem: open FOO should be open(FOO)
  648. =item * Precedence
  649. perl4 gives the special variable, C<$:> precedence, where perl5
  650. treats C<$::> as main C<package>
  651. $a = "x"; print "$::a";
  652. # perl 4 prints: -:a
  653. # perl 5 prints: x
  654. =item * Precedence
  655. perl4 had buggy precedence for the file test operators vis-a-vis
  656. the assignment operators. Thus, although the precedence table
  657. for perl4 leads one to believe C<-e $foo .= "q"> should parse as
  658. C<((-e $foo) .= "q")>, it actually parses as C<(-e ($foo .= "q"))>.
  659. In perl5, the precedence is as documented.
  660. -e $foo .= "q"
  661. # perl4 prints: no output
  662. # perl5 prints: Can't modify -e in concatenation
  663. =item * Precedence
  664. In perl4, keys(), each() and values() were special high-precedence operators
  665. that operated on a single hash, but in perl5, they are regular named unary
  666. operators. As documented, named unary operators have lower precedence
  667. than the arithmetic and concatenation operators C<+ - .>, but the perl4
  668. variants of these operators actually bind tighter than C<+ - .>.
  669. Thus, for:
  670. %foo = 1..10;
  671. print keys %foo - 1
  672. # perl4 prints: 4
  673. # perl5 prints: Type of arg 1 to keys must be hash (not subtraction)
  674. The perl4 behavior was probably more useful, if less consistent.
  675. =back
  676. =head2 General Regular Expression Traps using s///, etc.
  677. All types of RE traps.
  678. =over 5
  679. =item * Regular Expression
  680. C<s'$lhs'$rhs'> now does no interpolation on either side. It used to
  681. interpolate C<$lhs> but not C<$rhs>. (And still does not match a literal
  682. '$' in string)
  683. $a=1;$b=2;
  684. $string = '1 2 $a $b';
  685. $string =~ s'$a'$b';
  686. print $string,"\n";
  687. # perl4 prints: $b 2 $a $b
  688. # perl5 prints: 1 2 $a $b
  689. =item * Regular Expression
  690. C<m//g> now attaches its state to the searched string rather than the
  691. regular expression. (Once the scope of a block is left for the sub, the
  692. state of the searched string is lost)
  693. $_ = "ababab";
  694. while(m/ab/g){
  695. &doit("blah");
  696. }
  697. sub doit{local($_) = shift; print "Got $_ "}
  698. # perl4 prints: blah blah blah
  699. # perl5 prints: infinite loop blah...
  700. =item * Regular Expression
  701. Currently, if you use the C<m//o> qualifier on a regular expression
  702. within an anonymous sub, I<all> closures generated from that anonymous
  703. sub will use the regular expression as it was compiled when it was used
  704. the very first time in any such closure. For instance, if you say
  705. sub build_match {
  706. my($left,$right) = @_;
  707. return sub { $_[0] =~ /$left stuff $right/o; };
  708. }
  709. build_match() will always return a sub which matches the contents of
  710. C<$left> and C<$right> as they were the I<first> time that build_match()
  711. was called, not as they are in the current call.
  712. This is probably a bug, and may change in future versions of Perl.
  713. =item * Regular Expression
  714. If no parentheses are used in a match, Perl4 sets C<$+> to
  715. the whole match, just like C<$&>. Perl5 does not.
  716. "abcdef" =~ /b.*e/;
  717. print "\$+ = $+\n";
  718. # perl4 prints: bcde
  719. # perl5 prints:
  720. =item * Regular Expression
  721. substitution now returns the null string if it fails
  722. $string = "test";
  723. $value = ($string =~ s/foo//);
  724. print $value, "\n";
  725. # perl4 prints: 0
  726. # perl5 prints:
  727. Also see L<Numerical Traps> for another example of this new feature.
  728. =item * Regular Expression
  729. C<s`lhs`rhs`> (using backticks) is now a normal substitution, with no
  730. backtick expansion
  731. $string = "";
  732. $string =~ s`^`hostname`;
  733. print $string, "\n";
  734. # perl4 prints: <the local hostname>
  735. # perl5 prints: hostname
  736. =item * Regular Expression
  737. Stricter parsing of variables used in regular expressions
  738. s/^([^$grpc]*$grpc[$opt$plus$rep]?)//o;
  739. # perl4: compiles w/o error
  740. # perl5: with Scalar found where operator expected ..., near "$opt$plus"
  741. an added component of this example, apparently from the same script, is
  742. the actual value of the s'd string after the substitution.
  743. C<[$opt]> is a character class in perl4 and an array subscript in perl5
  744. $grpc = 'a';
  745. $opt = 'r';
  746. $_ = 'bar';
  747. s/^([^$grpc]*$grpc[$opt]?)/foo/;
  748. print ;
  749. # perl4 prints: foo
  750. # perl5 prints: foobar
  751. =item * Regular Expression
  752. Under perl5, C<m?x?> matches only once, like C<?x?>. Under perl4, it matched
  753. repeatedly, like C</x/> or C<m!x!>.
  754. $test = "once";
  755. sub match { $test =~ m?once?; }
  756. &match();
  757. if( &match() ) {
  758. # m?x? matches more then once
  759. print "perl4\n";
  760. } else {
  761. # m?x? matches only once
  762. print "perl5\n";
  763. }
  764. # perl4 prints: perl4
  765. # perl5 prints: perl5
  766. =back
  767. =head2 Subroutine, Signal, Sorting Traps
  768. The general group of Perl4-to-Perl5 traps having to do with
  769. Signals, Sorting, and their related subroutines, as well as
  770. general subroutine traps. Includes some OS-Specific traps.
  771. =over 5
  772. =item * (Signals)
  773. Barewords that used to look like strings to Perl will now look like subroutine
  774. calls if a subroutine by that name is defined before the compiler sees them.
  775. sub SeeYa { warn"Hasta la vista, baby!" }
  776. $SIG{'TERM'} = SeeYa;
  777. print "SIGTERM is now $SIG{'TERM'}\n";
  778. # perl4 prints: SIGTERM is main'SeeYa
  779. # perl5 prints: SIGTERM is now main::1
  780. Use B<-w> to catch this one
  781. =item * (Sort Subroutine)
  782. reverse is no longer allowed as the name of a sort subroutine.
  783. sub reverse{ print "yup "; $a <=> $b }
  784. print sort reverse a,b,c;
  785. # perl4 prints: yup yup yup yup abc
  786. # perl5 prints: abc
  787. =item * warn() won't let you specify a filehandle.
  788. Although it _always_ printed to STDERR, warn() would let you specify a
  789. filehandle in perl4. With perl5 it does not.
  790. warn STDERR "Foo!";
  791. # perl4 prints: Foo!
  792. # perl5 prints: String found where operator expected
  793. =back
  794. =head2 OS Traps
  795. =over 5
  796. =item * (SysV)
  797. Under HPUX, and some other SysV OSes, one had to reset any signal handler,
  798. within the signal handler function, each time a signal was handled with
  799. perl4. With perl5, the reset is now done correctly. Any code relying
  800. on the handler _not_ being reset will have to be reworked.
  801. Since version 5.002, Perl uses sigaction() under SysV.
  802. sub gotit {
  803. print "Got @_... ";
  804. }
  805. $SIG{'INT'} = 'gotit';
  806. $| = 1;
  807. $pid = fork;
  808. if ($pid) {
  809. kill('INT', $pid);
  810. sleep(1);
  811. kill('INT', $pid);
  812. } else {
  813. while (1) {sleep(10);}
  814. }
  815. # perl4 (HPUX) prints: Got INT...
  816. # perl5 (HPUX) prints: Got INT... Got INT...
  817. =item * (SysV)
  818. Under SysV OSes, C<seek()> on a file opened to append C<E<gt>E<gt>> now does
  819. the right thing w.r.t. the fopen() manpage. e.g., - When a file is opened
  820. for append, it is impossible to overwrite information already in
  821. the file.
  822. open(TEST,">>seek.test");
  823. $start = tell TEST ;
  824. foreach(1 .. 9){
  825. print TEST "$_ ";
  826. }
  827. $end = tell TEST ;
  828. seek(TEST,$start,0);
  829. print TEST "18 characters here";
  830. # perl4 (solaris) seek.test has: 18 characters here
  831. # perl5 (solaris) seek.test has: 1 2 3 4 5 6 7 8 9 18 characters here
  832. =back
  833. =head2 Interpolation Traps
  834. Perl4-to-Perl5 traps having to do with how things get interpolated
  835. within certain expressions, statements, contexts, or whatever.
  836. =over 5
  837. =item * Interpolation
  838. @ now always interpolates an array in double-quotish strings.
  839. print "To: [email protected]\n";
  840. # perl4 prints: To:[email protected]
  841. # perl5 errors : In string, @somewhere now must be written as \@somewhere
  842. =item * Interpolation
  843. Double-quoted strings may no longer end with an unescaped $ or @.
  844. $foo = "foo$";
  845. $bar = "bar@";
  846. print "foo is $foo, bar is $bar\n";
  847. # perl4 prints: foo is foo$, bar is bar@
  848. # perl5 errors: Final $ should be \$ or $name
  849. Note: perl5 DOES NOT error on the terminating @ in $bar
  850. =item * Interpolation
  851. Perl now sometimes evaluates arbitrary expressions inside braces that occur
  852. within double quotes (usually when the opening brace is preceded by C<$>
  853. or C<@>).
  854. @www = "buz";
  855. $foo = "foo";
  856. $bar = "bar";
  857. sub foo { return "bar" };
  858. print "|@{w.w.w}|${main'foo}|";
  859. # perl4 prints: |@{w.w.w}|foo|
  860. # perl5 prints: |buz|bar|
  861. Note that you can C<use strict;> to ward off such trappiness under perl5.
  862. =item * Interpolation
  863. The construct "this is $$x" used to interpolate the pid at that
  864. point, but now apparently tries to dereference C<$x>. C<$$> by itself still
  865. works fine, however.
  866. print "this is $$x\n";
  867. # perl4 prints: this is XXXx (XXX is the current pid)
  868. # perl5 prints: this is
  869. =item * Interpolation
  870. Creation of hashes on the fly with C<eval "EXPR"> now requires either both
  871. C<$>'s to be protected in the specification of the hash name, or both curlies
  872. to be protected. If both curlies are protected, the result will be compatible
  873. with perl4 and perl5. This is a very common practice, and should be changed
  874. to use the block form of C<eval{}> if possible.
  875. $hashname = "foobar";
  876. $key = "baz";
  877. $value = 1234;
  878. eval "\$$hashname{'$key'} = q|$value|";
  879. (defined($foobar{'baz'})) ? (print "Yup") : (print "Nope");
  880. # perl4 prints: Yup
  881. # perl5 prints: Nope
  882. Changing
  883. eval "\$$hashname{'$key'} = q|$value|";
  884. to
  885. eval "\$\$hashname{'$key'} = q|$value|";
  886. causes the following result:
  887. # perl4 prints: Nope
  888. # perl5 prints: Yup
  889. or, changing to
  890. eval "\$$hashname\{'$key'\} = q|$value|";
  891. causes the following result:
  892. # perl4 prints: Yup
  893. # perl5 prints: Yup
  894. # and is compatible for both versions
  895. =item * Interpolation
  896. perl4 programs which unconsciously rely on the bugs in earlier perl versions.
  897. perl -e '$bar=q/not/; print "This is $foo{$bar} perl5"'
  898. # perl4 prints: This is not perl5
  899. # perl5 prints: This is perl5
  900. =item * Interpolation
  901. You also have to be careful about array references.
  902. print "$foo{"
  903. perl 4 prints: {
  904. perl 5 prints: syntax error
  905. =item * Interpolation
  906. Similarly, watch out for:
  907. $foo = "array";
  908. print "\$$foo{bar}\n";
  909. # perl4 prints: $array{bar}
  910. # perl5 prints: $
  911. Perl 5 is looking for C<$array{bar}> which doesn't exist, but perl 4 is
  912. happy just to expand $foo to "array" by itself. Watch out for this
  913. especially in C<eval>'s.
  914. =item * Interpolation
  915. C<qq()> string passed to C<eval>
  916. eval qq(
  917. foreach \$y (keys %\$x\) {
  918. \$count++;
  919. }
  920. );
  921. # perl4 runs this ok
  922. # perl5 prints: Can't find string terminator ")"
  923. =back
  924. =head2 DBM Traps
  925. General DBM traps.
  926. =over 5
  927. =item * DBM
  928. Existing dbm databases created under perl4 (or any other dbm/ndbm tool)
  929. may cause the same script, run under perl5, to fail. The build of perl5
  930. must have been linked with the same dbm/ndbm as the default for C<dbmopen()>
  931. to function properly without C<tie>'ing to an extension dbm implementation.
  932. dbmopen (%dbm, "file", undef);
  933. print "ok\n";
  934. # perl4 prints: ok
  935. # perl5 prints: ok (IFF linked with -ldbm or -lndbm)
  936. =item * DBM
  937. Existing dbm databases created under perl4 (or any other dbm/ndbm tool)
  938. may cause the same script, run under perl5, to fail. The error generated
  939. when exceeding the limit on the key/value size will cause perl5 to exit
  940. immediately.
  941. dbmopen(DB, "testdb",0600) || die "couldn't open db! $!";
  942. $DB{'trap'} = "x" x 1024; # value too large for most dbm/ndbm
  943. print "YUP\n";
  944. # perl4 prints:
  945. dbm store returned -1, errno 28, key "trap" at - line 3.
  946. YUP
  947. # perl5 prints:
  948. dbm store returned -1, errno 28, key "trap" at - line 3.
  949. =back
  950. =head2 Unclassified Traps
  951. Everything else.
  952. =over 5
  953. =item * C<require>/C<do> trap using returned value
  954. If the file doit.pl has:
  955. sub foo {
  956. $rc = do "./do.pl";
  957. return 8;
  958. }
  959. print &foo, "\n";
  960. And the do.pl file has the following single line:
  961. return 3;
  962. Running doit.pl gives the following:
  963. # perl 4 prints: 3 (aborts the subroutine early)
  964. # perl 5 prints: 8
  965. Same behavior if you replace C<do> with C<require>.
  966. =item * C<split> on empty string with LIMIT specified
  967. $string = '';
  968. @list = split(/foo/, $string, 2)
  969. Perl4 returns a one element list containing the empty string but Perl5
  970. returns an empty list.
  971. =back
  972. As always, if any of these are ever officially declared as bugs,
  973. they'll be fixed and removed.