in reply to What does '::' mean in constructs '$::foo' and '@::foo'?
Hello jmeek, and welcome to the Monastery!
In Perl, the only truly global variables are those with predefined “punctuation” names: $/, $|, etc. (ok, also $a and $b). Other “global” variables (i.e., those with user-supplied names) are actually package-globals, meaning they are global within the package in which they are defined. In modern Perl, these variables are typically accessed in other packages via suitable our declarations, but the older mechanism of use vars is still available. Compare the following one-liners:
18:05 >perl -Mstrict -wE "package Foo; sub foo { say $x; } package mai +n; $x = 42; Foo::foo;" Global symbol "$x" requires explicit package name (did you forget to d +eclare "my $x"?) at -e line 1. Global symbol "$x" requires explicit package name (did you forget to d +eclare "my $x"?) at -e line 1. Bareword "Foo::foo" not allowed while "strict subs" in use at -e line +1. Execution of -e aborted due to compilation errors. 18:06 >perl -Mstrict -wE "use vars qw( $x ); package Foo; sub foo { sa +y $x; } package main; $x = 42; Foo::foo;" Global symbol "$x" requires explicit package name (did you forget to d +eclare "my $x"?) at -e line 1. Bareword "Foo::foo" not allowed while "strict subs" in use at -e line +1. Execution of -e aborted due to compilation errors. 18:06 >perl -Mstrict -wE "use vars qw( $x ); package Foo; sub foo { sa +y $::x; } package main; $x = 42; Foo::foo;" 42 18:06 >perl -Mstrict -wE "package Foo; sub foo { say $::x; } package m +ain; $x = 42; Foo::foo;" Variable "$x" is not imported at -e line 1. Global symbol "$x" requires explicit package name (did you forget to d +eclare "my $x"?) at -e line 1. Execution of -e aborted due to compilation errors. 18:06 >
In all cases, $x is actually $main::x; a use vars declaration doesn’t change that. In the third case, supplying the package name removes the error and allows package Foo to access the variable although it’s from a different package. (The final case is given to illustrate the role use vars is playing in preventing errors from use strict.)
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What does '::' mean in constructs '$::foo' and '@::foo'?
by locked_user sundialsvc4 (Abbot) on Oct 06, 2015 at 11:19 UTC |