Leaked source code of windows server 2003
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.

1538 lines
38 KiB

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