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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With