rtremaine has asked for the wisdom of the Perl Monks concerning the following question:

what does the syntax:

$::foo = 'foo';
mean and how is it different from:

$foo = 'foo';


thanks again

Replies are listed 'Best First'.
Re: syntax/operator question
by Zaxo (Archbishop) on Oct 05, 2004 at 05:56 UTC

    $::foo always refers to $main::foo, while $foo is the package variable $Namespace::foo for whatever your current namespace is. They may be identical, but not always.

    Perl always sees a variable name containing '::' as a fully qualified name.

    After Compline,
    Zaxo

      Even without a lexical $foo, and in package main, $foo may differ from $::foo:
      $ perl -we'package Foo; our $foo = 1; package main; $main::foo = 2; print "\$foo: $foo \$::foo $::foo\n"' $foo: 1 $::foo 2
Re: syntax/operator question
by tachyon (Chancellor) on Oct 05, 2004 at 05:56 UTC
    C:\>perl -MO=Deparse -e "$foo = 'bar'"; $foo = 'bar'; -e syntax OK C:\>perl -MO=Deparse -e "$main::foo = 'bar'"; $foo = 'bar'; -e syntax OK C:\>perl -MO=Deparse -e "$::foo = 'bar'"; $foo = 'bar'; -e syntax OK

    Update

    Superficially these all parse the same. But as Corion notes the :: is significant as it signifies a package rather than a lexical variable. As soon as your current package is not main but some other package, or as soon as $foo is a lexical variable (and $::foo will never be) they are different.

    C:\>perl -MO=Deparse -e "package Foo; my $foo = 'bar'"; package Foo; my $foo = 'bar'; -e syntax OK C:\>perl -MO=Deparse -e "package Foo; my $::foo = 'bar'"; "my" variable $::foo can't be in a package at -e line 1, near "my $::f +oo " Can't use global $::foo in "my" at -e line 1, near "my $::foo " -e had compilation errors. C:\>perl -e "package Foo; $::foo = 'foo'; print $foo" C:\>perl -e "package Foo; $::foo = 'foo'; print $main::foo" foo C:\>

    cheers

    tachyon

Re: syntax/operator question
by mifflin (Curate) on Oct 05, 2004 at 05:55 UTC
    assuming $foo is a package variable (not a lexical) and $foo is in the main package, they are the same.