What's the difference between these two definitions?
Question
Why it's a syntax error:
my @hash{1..4}=(1..4);
but not this one:
my %hash;
@hash{1..4}=(1..4);
Solution
the 1st example is of a lexically scoped 'my' + a hash slice which pre-supposes that one can declare a hash in the manner of a slice which is not valid syntax. your 2nd example is appropriate, declaring the hash first, assuming that you're use'ing strict + warnings;
OTHER TIPS
my
requires a variable or a list of variable in parens as argument.
@hash{1..4}
is neither of those, so
my @hash{1..4}
is a syntax error.
First example fails, because hash slice is an operation that returns some result. Obviously, perpending it with my
declaration makes no sense, just like writing something like my 2+2
wouldn't. my
must be followed by list of variables to declare.
Second example does just that - declares a hash in current scope and then accesses a slice of it.