Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: To initialise or not to initialise?

by skyknight (Hermit)
on Jun 24, 2004 at 15:38 UTC ( #369401=note: print w/replies, xml ) Need Help??


in reply to To initialise or not to initialise?

Initialization is not simply a preference thing. Depending on the life time of your execution environment, not initializing things can get you into trouble, though I think you might be a little confused about when it matters.

The only time that things are "reused" is in the case of things like mod_perl where the same handler may be used to serve multiple requests, and this is only in the case of global variables. If you have a variable that is scoped to a subroutine with "my", then it will always be initialized to undef when the subroutine is invoked, or to whatever value you specify.

Where you can get into trouble is with subroutines that reference global variables, making the assumption that they are set to an undef state every time the subroutine is invoked. In the case of a one-shot Perl script, you can get away with this because the variable is in fact undef. With mod_perl, however, things might work as you expect the first time, but then crash on subsequent requests because the first invocation of the handler left stuff in the global variable, and the subsequent invocations of the handler assumed that the global was undef but it was not.

For the most part, you should just avoid using global variables. However, as I mentioned in another post here, sometimes globals are legitimate, to a degree. Specifically, package wide variables make sense in many cases, and parallel the concept of "static member variables" in other languages. What you might declare in Java within a class as

static int commonFoo = 0;

would be declared in Perl as a package wide variable. A simple use for such a construct would be if you wanted to keep track of the number of objects of a certain type that had been allocated, then you might have your constructor for that class increment a package wide variable whenver it was invoked. As a more concrete example, in a RDMBS-OO mapper framework that I'm presently writing, I have the base class for objects maintain a hash array that holds the schemas for the database tables. There is no sense in each object holding its own copy of it. It's common to all instances of the class, and thus should live in a common place.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (6)
As of 2021-10-18 15:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (74 votes). Check out past polls.

    Notices?