NAME

perltrap - Perl traps for the unwary

DESCRIPTION

The biggest trap of all is forgetting to usewarnings
or use the -w
switch; see perllexwarn and perlrun. The second biggest trap is not
making your entire program runnable under usestrict
. The third biggest
trap is not reading the list of changes in this version of Perl; see
perldelta.

Awk Traps

Accustomed awk users should take special note of the following:

A Perl program executes only once, not once for each input line. You can
do an implicit loop with -n
or -p
.

You have to decide whether you want to use string or numeric
comparisons.

Reading an input line does not split it for you. You get to split it
to an array yourself. And the split() operator has different
arguments than awk's.

The current input line is normally in $_, not $0. It generally does
not have the newline stripped. ($0 is the name of the program
executed.) See perlvar.

$<digit> does not refer to fields--it refers to substrings matched
by the last match pattern.

The print() statement does not add field and record separators unless
you set $,
and $\
. You can set $OFS and $ORS if you're using
the English module.

You must open your files before you print to them.

The range operator is "..", not comma. The comma operator works as in
C.

The match operator is "=~", not "~". ("~" is the one's complement
operator, as in C.)

The exponentiation operator is "**", not "^". "^" is the XOR
operator, as in C. (You know, one could get the feeling that awk is
basically incompatible with C.)

The concatenation operator is ".", not the null string. (Using the
null string would render /pat/ /pat/
unparsable, because the third slash
would be interpreted as a division operator--the tokenizer is in fact
slightly context sensitive for operators like "/", "?", and ">".
And in fact, "." itself can be the beginning of a number.)

Perl Traps

Practicing Perl Programmers should take note of the following:

Remember that many operations behave differently in a list
context than they do in a scalar one. See perldata for details.

Avoid barewords if you can, especially all lowercase ones.
You can't tell by just looking at it whether a bareword is
a function or a string. By using quotes on strings and
parentheses on function calls, you won't ever get them confused.

You cannot discern from mere inspection which builtins
are unary operators (like chop() and chdir())
and which are list operators (like print() and unlink()).
(Unless prototyped, user-defined subroutines can only be list
operators, never unary ones.) See perlop and perlsub.

People have a hard time remembering that some functions
default to $_, or @ARGV, or whatever, but that others which
you might expect to do not.

The <FH> construct is not the name of the filehandle, it is a readline
operation on that handle. The data read is assigned to $_ only if the
file read is the sole condition in a while loop:

Remember not to use =
when you need =~
;
these two constructs are quite different:

$x = /foo/;

$x =~ /foo/;

The do{}
construct isn't a real loop that you can use
loop control on.

Use my() for local variables whenever you can get away with
it (but see perlform for where you can't).
Using local() actually gives a local value to a global
variable, which leaves you open to unforeseen side-effects
of dynamic scoping.

If you localize an exported variable in a module, its exported value will
not change. The local name becomes an alias to a new value but the
external name is still an alias for the original.

Perl4 to Perl5 Traps

Practicing Perl4 Programmers should take note of the following
Perl4-to-Perl5 specific traps.

They're crudely ordered according to the following list:

Discontinuance, Deprecation, and BugFix traps

Anything that's been fixed as a perl4 bug, removed as a perl4 feature
or deprecated as a perl4 feature with the intent to encourage usage of
some other perl5 feature.

Traps related to the precedence of parsing, evaluation, and execution of
code.

General Regular Expression Traps using s///, etc.

Traps related to the use of pattern matching.

Subroutine, Signal, Sorting Traps

Traps related to the use of signals and signal handlers, general subroutines,
and sorting, along with sorting subroutines.

OS Traps

OS-specific traps.

DBM Traps

Traps specific to the use of dbmopen(), and specific dbm implementations.

Unclassified Traps

Everything else.

If you find an example of a conversion trap that is not listed here,
please submit it to <perlbug@perl.org> for inclusion.
Also note that at least some of these can be caught with the
usewarnings
pragma or the -w switch.

Discontinuance, Deprecation, and BugFix traps

Anything that has been discontinued, deprecated, or fixed as
a bug from perl4.

The meaning of foreach{}
has changed slightly when it is iterating over a
list which is not an array. This used to assign the list to a
temporary array, but no longer does so (for efficiency). This means
that you'll now be iterating over the actual values, not over copies of
the values. Modifications to the loop variable can change the original
values.

Perl 4 would ignore any text which was attached to an -e switch,
always taking the code snippet from the following arg. Additionally, it
would silently accept an -e switch without a following arg. Both of
these behaviors have been fixed.

In Perl 4 the return value of push was undocumented, but it was
actually the last value being pushed onto the target list. In Perl 5
the return value of push is documented, but has changed, it is the
number of elements in the resulting list.

In Perl 4, if in list context the delimiters to the first argument of
split() were ??
, the result would be placed in @_
as well as
being returned. Perl 5 has more respect for your subroutine arguments.

# perl5 warns: "Useless use of a constant in void context" if using -w

String interpolation of $#array
differs

String interpolation of the $#array
construct differs when braces
are to used around the name.

@a = (1..3);

print "${#a}";

# perl4 prints: 2

# perl5 fails with syntax error

@ = (1..3);

print "$#{a}";

# perl4 prints: {a}

# perl5 prints: 2

Perl guesses on map, grep followed by { if it starts BLOCK or hash ref

When perl sees map { (or grep {), it has to guess whether the {
starts a BLOCK or a hash reference. If it guesses wrong, it will report
a syntax error near the } and the missing (or unexpected) comma.

Use unary +
before { on a hash reference, and unary +
applied
to the first thing in a BLOCK (after {), for perl to guess right all
the time. (See map.)

Numerical Traps

Perl4-to-Perl5 traps having to do with numerical operators,
operands, or output from same.

Formatted output and significant digits

Formatted output and significant digits. In general, Perl 5
tries to be more precise. For example, on a Solaris Sparc:

print 7.373504 - 0, "\n";

printf "%20.18f\n", 7.373504 - 0;

# Perl4 prints:

7.3750399999999996141

7.375039999999999614

# Perl5 prints:

7.373504

7.375039999999999614

Notice how the first result looks better in Perl 5.

Your results may vary, since your floating point formatting routines
and even floating point format may be slightly different.

Auto-increment operator over signed int limit deleted

This specific item has been deleted. It demonstrated how the auto-increment
operator would not catch when a number went over the signed int limit. Fixed
in version 5.003_04. But always be wary when using large integers.
If in doubt:

When bitwise operators which can operate upon either numbers or
strings (& | ^ ~
) are given only strings as arguments, perl4 would
treat the operands as bitstrings so long as the program contained a call
to the vec() function. perl5 treats the string operands as bitstrings.
(See "Bitwise String Operators" in perlop for more details.)

$fred = "10";

$barney = "12";

$betty = $fred & $barney;

print "$betty\n";

# Uncomment the next line to change perl4's behavior

# ($dummy) = vec("dummy", 0, 0);

# Perl4 prints:

8

# Perl5 prints:

10

# If vec() is used anywhere in the program, both print:

10

General data type traps

Perl4-to-Perl5 traps involving most data-types, and their usage
within certain expressions and/or context.

Negative array subscripts now count from the end of array

Negative array subscripts now count from the end of the array.

@a = (1,2,3,4,5);

print"The third element of the array is $a[3] also expressed as $a[-2] \n";

# perl4 prints: The third element of the array is 4 also expressed as

# perl5 prints: The third element of the array is 4 also expressed as 4

Setting $#array
lower now discards array elements

Setting $#array
lower now discards array elements, and makes them
impossible to recover.

Assigning undef to a glob has no effect in Perl 5. In Perl 4
it undefines the associated scalar (but may have other side effects
including SEGVs). Perl 5 will also warn if undef is assigned to a
typeglob. (Note that assigning undef to a typeglob is different
than calling the undef function on a typeglob (undef*foo
), which
has quite a few effects.

Precedence Traps

Perl4-to-Perl5 traps involving precedence order.

Perl 4 has almost the same precedence rules as Perl 5 for the operators
that they both have. Perl 4 however, seems to have had some
inconsistencies that made the behavior differ from what was documented.

LHS vs. RHS of any assignment operator

LHS vs. RHS of any assignment operator. LHS is evaluated first
in perl4, second in perl5; this can affect the relationship
between side-effects in sub-expressions.

Precedence of assignment operators same as the precedence of assignment

The precedence of assignment operators is now the same as the precedence
of assignment. Perl 4 mistakenly gave them the precedence of the associated
operator. So you now must parenthesize them in expressions like

perl4 had buggy precedence for the file test operators vis-a-vis
the assignment operators. Thus, although the precedence table
for perl4 leads one to believe -e $foo .= "q"
should parse as
((-e $foo) .= "q")
, it actually parses as (-e ($foo .= "q"))
.
In perl5, the precedence is as documented.

In perl4, keys(), each() and values() were special high-precedence operators
that operated on a single hash, but in perl5, they are regular named unary
operators. As documented, named unary operators have lower precedence
than the arithmetic and concatenation operators + - ., but the perl4
variants of these operators actually bind tighter than + - ..
Thus, for:

Currently, if you use the m//o qualifier on a regular expression
within an anonymous sub, all closures generated from that anonymous
sub will use the regular expression as it was compiled when it was used
the very first time in any such closure. For instance, if you say

OS Traps

SysV resets signal handler correctly

Under HPUX, and some other SysV OSes, one had to reset any signal handler,
within the signal handler function, each time a signal was handled with
perl4. With perl5, the reset is now done correctly. Any code relying
on the handler _not_ being reset will have to be reworked.

Under SysV OSes, seek() on a file opened to append >>
now does
the right thing w.r.t. the fopen() manpage. e.g., - When a file is opened
for append, it is impossible to overwrite information already in
the file.

Creation of hashes on the fly with eval"EXPR"
now requires either both
$
's to be protected in the specification of the hash name, or both curlies
to be protected. If both curlies are protected, the result will be compatible
with perl4 and perl5. This is a very common practice, and should be changed
to use the block form of eval{} if possible.

perl4 programs which unconsciously rely on the bugs in earlier perl versions.

perl -e '$bar=q/not/; print "This is $foo{$bar} perl5"'

# perl4 prints: This is not perl5

# perl5 prints: This is perl5

Array and hash brackets during interpolation

You also have to be careful about array and hash brackets during
interpolation.

print "$foo["

perl 4 prints: [

perl 5 prints: syntax error

print "$foo{"

perl 4 prints: {

perl 5 prints: syntax error

Perl 5 is expecting to find an index or key name following the respective
brackets, as well as an ending bracket of the appropriate type. In order
to mimic the behavior of Perl 4, you must escape the bracket like so.

DBM Traps

General DBM traps.

Perl5 must have been linked with same dbm/ndbm as the default for dbmopen()

Existing dbm databases created under perl4 (or any other dbm/ndbm tool)
may cause the same script, run under perl5, to fail. The build of perl5
must have been linked with the same dbm/ndbm as the default for dbmopen()
to function properly without tie'ing to an extension dbm implementation.

DBM exceeding limit on the key/value size will cause perl5 to exit immediately

Existing dbm databases created under perl4 (or any other dbm/ndbm tool)
may cause the same script, run under perl5, to fail. The error generated
when exceeding the limit on the key/value size will cause perl5 to exit
immediately.