Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re:Behavior of 'our' variables in the package-namespace

by GrandFather (Saint)
on Nov 02, 2015 at 02:24 UTC ( [id://1146650]=note: print w/replies, xml ) Need Help??


in reply to Behavior of 'our' variables in the package-namespace

Without the BEGIN your code looks somewhat like:

my $foobar_o = Foo::Bar->new("object o"); printf "%s\n", $foobar_o->text(1); # some random stuff our $data = { 1 => "one", 2 => "two", 100 => "one hundred", }; # some more random stuff

from which you can see the initialization of $data doesn't happen until after the call to text. Nothing to do with our versus my. Put the package at the top of the file and educate your users, or stick with the BEGIN. In either case "my" would be better than "our" in the context shown.

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: Behavior of 'our' variables in the package-namespace
by Apero (Scribe) on Nov 02, 2015 at 02:48 UTC

    Ah, thanks for the reply! Yes, I realized the definition of $Foo::Bar::data never occurred in time without BEGIN, but I didn't realize that non-subroutine code, even within package definitions was "not special." I'm so used to subs getting declared after they're referenced, but of course the compiler knew about them when the script was processed.

    I probably need to think of packages less as an atomic collection of variables, subroutines, and code, and more as a strict division of namespaces. The code that I'm calling in BEGIN above obviously needs to happen before the method that needs it, and I somehow expected the compiler to magically deal with that. What fun would it be if Perl did all my work for me? ;) I read that in the docs for require() but I guess it didn't make sense until you broke it down a bit more directly.

    The hint about our() was very useful, thanks! I was under the impression that our was needed to get persistent data in a package namespace, but it seems that only allows the variable to be referenced from another class, clearly not required in well-designed OO code where accessors and methods are supposed to hide such details. There's no point in creating true globals across packages needlessly.

    Thanks again for the reply!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1146650]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-16 20:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found