A Hash is just a list of key, value pairs. There is a syntax construct to help differentiate the keys from the values. It is known as a "fat arrow" =>
. This construct forces the left hand argument into a string, and then gets transformed into a simple comma.
This is what you meant to write:
perl -MO=Deparse -e'$s = { a => 1 }'
$s = {'a', 1};
-e syntax OK
This is what you actually wrote:
perl -MO=Deparse -e'$s = { a = 1 }'
Can't modify constant item in scalar assignment at -e line 1, near "1 }"
-e had compilation errors.
$s = {'a' = 1};
This is why it I would recommend you always start out a Perl program with warnings enabled.
perl -w -MO=Deparse -e'$s = { a = 1 }'
Unquoted string "a" may clash with future reserved word at -e line 1.
Can't modify constant item in scalar assignment at -e line 1, near "1 }"
-e had compilation errors.
BEGIN { $^W = 1; }
$s = {'a' = 1};
perl -w -MO=Deparse -e'$s = { a => 1 }'
Name "main::s" used only once: possible typo at -e line 1.
BEGIN { $^W = 1; }
my $s = {'a', 1};
-e syntax OK
This last example shows why you should also use strict
.
perl -w -Mstrict -MO=Deparse -e'$s = { a => 1 }'
Global symbol "$s" requires explicit package name at -e line 1.
-e had compilation errors.
BEGIN { $^W = 1; }
use strict 'refs';
${'s'} = {'a', 1};
I should have declared $s
before trying to use it:
perl -w -Mstrict -MO=Deparse -e'my $s = { a => 1 }'
BEGIN { $^W = 1; }
use strict 'refs';
my $s = {'a', 1};
-e syntax OK
This is why I always start out my Perl programs with:
use strict;
use warnings;