2

Why it's a syntax error:

my @hash{1..4}=(1..4);

but not this one:

my %hash;
@hash{1..4}=(1..4);
bolbol
  • 325
  • 3
  • 9

3 Answers3

6

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;

shinronin
  • 193
  • 8
  • This is a syntax error question, not a "variables must be declared (must exist) to be used" question. You can slice-assign to a hash that didn't previously exist: `perl -E '%h{1..4}=(); say for keys %h;'`. The OP's problem is that you can't `my` declare *and* access elements in the same statement. – pilcrow Jun 14 '12 at 15:18
  • correct, which i thought was implicit in what i said. perhaps not, hence why i linked to the perldata slice page. – shinronin Jun 14 '12 at 15:44
  • The way you've phrased your answer make it seem (to me) that you are identifying the non-existence of `%hash` as the issue, rather than the syntactically botched declaration as the issue. – pilcrow Jun 14 '12 at 16:18
  • :shrug: other folks seem to have understood and my answer was accepted so it appears what i said was sufficient for the OP. but i can see where my quick explanation didn't completely lay out the semantic differences between syntax, data structure, and slice. – shinronin Jun 14 '12 at 16:35
  • @ikegami i've redone my post. i look forward to more polite, friendly, and constructive comments from you in the future. – shinronin Jun 14 '12 at 18:47
  • Comments and -1 retracted as they no longer apply. – ikegami Jun 14 '12 at 18:55
5

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.

ikegami
  • 367,544
  • 15
  • 269
  • 518
3

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.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
  • `$a` is also an operation that returns some result, yet you can place a `my` in front of it. This is not a correct answer, although it's close. – ikegami Jun 14 '12 at 16:20
  • "my must be followed by list of variables to declare" should cover what exactly `my` is valid with. – Oleg V. Volkov Jun 14 '12 at 16:23
  • It's the first sentence I commented on. (Although that one is not quite right either: `my $x, $y` doesn't do what you said it does.) – ikegami Jun 14 '12 at 16:25
  • Well, I'll just add a link to `my`, so I don't have to quote it entirely. – Oleg V. Volkov Jun 14 '12 at 16:28