Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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?

Comment on Perl syntax
Select or Download Code
Reaped: Re: Perl syntax
by NodeReaper (Curate) on Mar 27, 2012 at 01:46 UTC
Re: Perl syntax
by chromatic (Archbishop) on Mar 27, 2012 at 01:46 UTC
Re: Perl syntax
by stevieb (Deacon) 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 kcott (Abbot) 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

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://961806]
Approved by kcott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (12)
As of 2015-07-07 15:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (90 votes), past polls