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

i don't understand why the package variables are vivificated _before_ the require.

it looks like aaa::var defines a variable in namespace aaa. (and vivificates it if the package is not yet defined)

thanks

:::::::::::::: perlexe.pl :::::::::::::: #!/usr/bin/perl use strict; use warnings; BEGIN { $perlpkg::var_our = "foo"; $perlpkg::var_my = "foo"; $perlpkg::var_lcl = "foo"; } print "\noml : $perlpkg::var_our $perlpkg::var_my $perlpkg::var_lcl\n" +; require "perlpkg.pm"; $perlpkg::var_our = "bar"; $perlpkg::var_my = "bar"; $perlpkg::var_lcl = "bar"; print "oml : $perlpkg::var_our $perlpkg::var_my $perkpkg::var_lcl\n\n" +; :::::::::::::: perlpkg.pm :::::::::::::: package perlpkg; our $var_our; my $var_my ; local $var_lcl; print " oml : $var_our $var_my $var_lcl\n"; $var_our = "baz"; $var_my = "baz"; $var_lcl = "baz"; print " oml : $var_our $var_my $var_lcl\n"; 1; STDOUT : oml : foo foo foo oml : foo oml : baz baz baz oml : bar bar

Replies are listed 'Best First'.
Re: vivification of package variables
by GrandFather (Saint) on Sep 21, 2010 at 05:42 UTC

    Despite the names, all your *::* style variables are package variables which pop into existence when they are used. Consider:

    use strict; use warnings; $main::var_my = "foo1"; my $var_my = "foo2"; print "Lexical: $var_my\n"; print "Package: $main::var_my\n";

    Prints:

    Lexical: foo2 Package: foo1
    True laziness is hard work
Re: vivification of package variables
by ikegami (Patriarch) on Sep 21, 2010 at 05:34 UTC
    Just mentioning its name is enough to vivify it. (You're going far beyond that and assigning a value to it!) Using a symbolic reference doesn't vivify it until the reference evaluated.
    >perl -le"$pkg::var1; $pkg::{'var2'}; print for keys %pkg::;" var1

    I'm not sure I understand your disconnect. Do you think

    $pkg::var = "foo"; package pkg; print $var;

    is different than

    package pkg; $var = "foo"; print $var;

    They're not.

Re: vivification of package variables
by JavaFan (Canon) on Sep 21, 2010 at 09:56 UTC
    From a language point of view, all namespaces always exist. In fact, all package variables exist as well - the implementation just delays creating the internal bookkeeping associated with variables until they're actually encountered. The keyword package doesn't create much (just an entry in the stash, if existing already); it's main effect is compile time: it just sets the default package name non-lexical, not-special names live in until the end of the current scope, or the next package statement - whatever comes first.