[Israel.pm] use constant and our

Adriano Ferreira a.r.ferreira at gmail.com
Wed Mar 4 16:22:07 PST 2009


On Wed, Mar 4, 2009 at 9:16 PM, Adriano Ferreira <a.r.ferreira at gmail.com> wrote:
> On Wed, Mar 4, 2009 at 8:59 PM, Gaal Yahas <gaal at forum2.org> wrote:
>> Minor correction: "our" is lexically scoped, so you need:
>
> No, it is not.
>
> $ perl -le ' our $foo = 3; { our $foo = 4; } print $foo '
> 4
>
> "our" is package scoped. If you refer to the same package/our variable
> name, it is the same variable.

Also contrast this to:

perl -le 'my $foo = 3; { my $foo = 4; } print $foo '
3

I understand that my explanation was a bit misleading because for a
similar block with "my" that could not be translated with repeated
"my" statements.

my $foo = 0;
BEGIN { my $foo = 3; } # this $foo is another variable which does not
mess with the first one

BEGIN { $foo = 1 } # this is an assignment to the first one

which when executed leads to the amazing result:

$ perl -le 'my $foo = 0; BEGIN { my $foo = 3 } BEGIN { $foo = 1 } print $foo'
0

because assigning 1 to $foo at compile-time (by BEGIN) gets wiped at
runtime by the simple assignment.




>> our @list;
>>
>> BEGIN {
>>  @list = qw(one two three);
>> }
>>
>> use constant .......;
>>
>> On Thu, Mar 5, 2009 at 12:07 AM, 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?
>>>
>>> Tested on Perl 5.6.
>>>
>>> Shmuel.
>>> _______________________________________________
>>> Perl mailing list
>>> Perl at perl.org.il
>>> http://perl.org.il/mailman/listinfo/perl
>>>
>>
>>
>>
>> --
>> Gaal Yahas <gaal at forum2.org>
>> http://gaal.livejournal.com/
>> _______________________________________________
>> Perl mailing list
>> Perl at perl.org.il
>> http://perl.org.il/mailman/listinfo/perl
>>
>



More information about the Perl mailing list