[Israel.pm] use constant and our

Adriano Ferreira a.r.ferreira at gmail.com
Wed Mar 4 14:41:55 PST 2009


On Wed, Mar 4, 2009 at 7:07 PM, Shmuel Fomberg <semuelf at 012.net.il> wrote:
> Hi All.
>
> Today I've seen a weird behavior in a program. I had something like:
>
> our @list = qw{one two three};
>
> use constant VAR => {
>    key => "value",
>    map( { ( $_ => 16 ) } @list ),
>    key2 => "value2",
> };
>
> To my surprise, VAR contained only key and key2.
> I theorized that it is because "use constant" is set in compile time,
> and @list is empty in that time. @list is populated in run-time, but
> that is too late for VAR.
>
> Am I right or is there other reason for this?

Yes, that is exactly what happened. If you use the "our" statement
within a BEGIN:

BEGIN {
     our  @list = qw{one two three};
}

you can make it work as you thought at first.

The BEGIN blocks and use statements (as you already said contrasting
compile-time and run-time) create a different order of execution
besides the textual one, which is quite surprising some times.

It is like you have written:

BEGIN {

our @list;  # the declarations happen at compile time, so that the
references down below don't err on "strict" mode

require constant;
constant->import( VAR => {
   key => "value",
   map( { ( $_ => 16 ) } @list ),
   key2 => "value2",
});

}

# then everything else not in a "BEGIN"

@list = qw{one two three};



> Tested on Perl 5.6.

It is not different in Perl 5.8 or 5.10.

Regards,
Adriano


> Shmuel.
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
>



More information about the Perl mailing list