Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Perl syntax

by PerlOnTheWay (Scribe)
on Mar 27, 2012 at 01:28 UTC ( #961806=perlquestion: print w/replies, xml ) Need Help??
PerlOnTheWay has asked for the wisdom of the Perl Monks concerning the following question:

package A; package B; our $d = 1; package C; package D; print $d;

the above prints 1,but how does it work actually?

$d is not defined in package D, how can it be printed directly?

Replies are listed 'Best First'.
Re: Perl syntax
by stevieb (Abbot) on Mar 27, 2012 at 01:58 UTC

    From 'perldoc -f our'

    An "our" declaration declares a global variable that will be visible a +cross its entire lexical scope, even across package boundaries.

    So any variable initialized with my or our is in this case within file scope. Wrap the instantiation of $d within a block to make the scope smaller:

    package A; package B; { our $d = 1; } package C; package D; # now you have to use the package name to access the var print $B::d;
Re: Perl syntax
by chromatic (Archbishop) on Mar 27, 2012 at 01:46 UTC
Re: Perl syntax
by JavaFan (Canon) on Mar 27, 2012 at 09:19 UTC
    our makes a lexically scoped alias to a package variable. So,
    package B; our $d = 1;
    means that for the rest of the lexical scope (in your case, the current file (and of course not if it's hidden by a definition in an inner scope)), $d is an alias to $B::d. So, your code is equivalent to:
    package A; package B; $B::d = 1; package C; package D; print $B::d;
    Don't worry if you find it confusing; many people do. Luckely, you don't have to use it. I find myself using it only for variables like @ISA and @EXPORT.
Re: Perl syntax
by kcott (Chancellor) on Mar 27, 2012 at 02:00 UTC

    See our for more details; including an example similar to yours. (Note: that's a different our link to what chromatic provides above.)

    -- Ken

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://961806]
Approved by kcott
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2018-04-26 22:11 GMT
Find Nodes?
    Voting Booth?