From 9b12f83b0b65827942028a14ac697977b5a83f3f Mon Sep 17 00:00:00 2001 From: Father Chrysostomos Date: Mon, 3 Jun 2013 20:48:00 -0700 Subject: [PATCH] Traps for the unwary JS programmer (perltrap.pod) This is part of ticket #117507 or #109408, whichever you like. This incorporates suggestions and corrections from Ronald Kimball and Tom Christiansen. Thank them! --- pod/perltrap.pod | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) diff --git a/pod/perltrap.pod b/pod/perltrap.pod index ee17470..d55e77a 100644 --- a/pod/perltrap.pod +++ b/pod/perltrap.pod @@ -276,6 +276,101 @@ for numeric comparisons. =back +=head2 JavaScript Traps + +Judicious JavaScript programmers should take note of the following: + +=over 4 + +=item * + +In Perl, binary C<+> is always addition. C<$string1 + $string2> converts +both strings to numbers and then adds them. To concatenate two strings, +use the C<.> operator. + +=item * + +The C<+> unary operator doesn't do anything in Perl. It exists to avoid +syntactic ambiguities. + +=item * + +Unlike C, Perl's C (also spelled C) does not allow +the left-hand side to be an arbitrary expression. It must be a variable: + + for my $variable (keys %hash) { + ... + } + +Furthermore, don't forget the C in there, as +C iterates over the keys and values, and is +generally not useful ($kv would be a key, then a value, and so on). + +=item * + +To iterate over the indices of an array, use C. C iterates over the values. + +=item * + +Perl requires braces following C, C, C, etc. + +=item * + +In Perl, C is spelled C. + +=item * + +C has higher precedence than assignment. In JavaScript, one can +write: + + condition ? do_something() : variable = 3 + +and the variable is only assigned if the condition is false. In Perl, you +need parentheses: + + $condition ? do_something() : ($variable = 3); + +Or just use C. + +=item * + +Perl requires semicolons to separate statements. + +=item * + +Variables declared with C only affect code I the declaration. +You cannot write C<$x = 1; my $x;> and expect the first assignment to +affect the same variable. It will instead assign to an C<$x> declared +previously in an outer scope, or to a global variable. + +Note also that the variable is not visible until the following +I. This means that in C the second $x refers +to one declared previously. + +=item * + +C variables are scoped to the current block, not to the current +function. If you write C<{my $x;} $x;>, the second C<$x> does not refer to +the one declared inside the block. + +=item * + +An object's members cannot be made accessible as variables. The closest +Perl equivalent to C is C, which can alias +C<$_> to the object: + + for ($object) { + $_->method; + } + +=item * + +The object or class on which a method is called is passed as one of the +method's arguments, not as a separate C value. + +=back + =head2 Perl Traps Practicing Perl Programmers should take note of the following: -- 2.7.4