Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: hash does not allow alphanumeric keys in this special case

Tags:

hash

quoting

perl

I find a strange behaviour by creating a hash:

perl -e "%x = (1 => 10, p2 => 20); while ( ($k,$v) = each %x ) { print \"key $k value $v\n\";}"

gives the following output:

key p2 value 20
key 1 value 10

But if I change the key p2 to 1p2 I get an error:

perl -e "%x = (1 => 10, 1p2 => 20); while ( ($k,$v) = each %x ) { print \"key $k value $v\n\";}"

The output is:

syntax error at -e line 1, near "1p2"
Execution of -e aborted due to compilation errors.

Why does it give an error?

(Win10, Strawberry Perl v5.30.0)

like image 377
giordano Avatar asked Dec 13 '22 08:12

giordano


1 Answers

To quote from perlop (Emphasis added):

The "=>" operator (sometimes pronounced "fat comma") is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behavior, the left operand can be quoted explicitly.

Since 1p2 begins with a digit, that special behavior of => doesn't apply. You have to quote it like a normal string to prevent the parse error.

like image 101
Shawn Avatar answered Jan 04 '23 23:01

Shawn