Search code examples
perlhashscopeslicevariable-declaration

Perl: Hash slices cannot be lexically scoped


I have really no idea, why this is wrong:

#!/usr/bin/perl
use v5.20;
package MyDate;
sub new{ bless {}, shift; }
sub AUTOLOAD{
    my $f = our $AUTOLOAD;
    my @h{qw[Wday Month Year]} = (localtime)[3,4,5];
}

Err:compilation error near "@h{"


If I delete my (or even if package-scoped with our):

@h{qw[Wday Month Year]} = (localtime)[3,4,5];

It will magically works. Why cannot be hash slices lexically scoped?

Edit: Yes - I have not noticed, that (localtime)[3] = mday not wday. But that is not the point. I am asking about the scope, not localtime func.

Edit2: The hash %h (the point of my question), is intended to be used inside the autoload sub (well, of course when I am trying to use it as hash slice there). Just for clarity.


Solution

  • @h{...} is not a variable, so you can't declare it as such.

    @h{...} = ...; sets elements of %h. So it's %h you need to create.

    This is done as follows:

    my %h;
    

    By the way, I doubt you have a legitimate reason for using AUTOLOAD. Keep in mind that code at the top level (at the file level) of a module will be executed when the module is first loaded in an interpreter.