Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: To initialise or not to initialise?

by melora (Scribe)
on Jun 24, 2004 at 15:27 UTC ( [id://369394]=note: print w/replies, xml ) Need Help??


in reply to To initialise or not to initialise?

I find quite often that my old C habits are actually preventing me from using features in Perl.

For instance, I tend to initialize all variables when I declare them, because in C an uninitialized variable can, and usually does, contain garbage. However, this takes away the helpful "use of uninitialized variable" warning, so what worked for me in C really works *against* me in Perl. (Although the point about initializing to a default value is well taken)

Another habit I have is that of declaring all global variables at the top of the file. This can lead to having to go to the top of a file to find out about a variable that is used down in the body of the code somewhere. Then again, as has been pointed out already, that can be due to a poor variable name. On the other hand, if I don't have it at the top of the file, I have to go find it. I think part of this dilemma, for me, goes back to the following:

I still tend to use a lot of global variables, and I'm working at making variables just where I need them. (Keeps the "namespace" less cluttered? I'm still learning the lingo.) The classic example, for me, is the index variable of a for loop. No need, generally, to have it defined anywhere but within the loop, so why make it global? ("lexical" is the word I need?) And now that I've started learning about how to do OO programming in Perl, I can really start to "encapsulate" and avoid globals still more.

So I guess I'm just a recovering C addict. Thanks to the supportive Perl Monastery community, though, I'm beginning to kick the habit.

Replies are listed 'Best First'.
Re^2: To initialise or not to initialise?
by iburrell (Chaplain) on Jun 24, 2004 at 16:01 UTC
    Are you really using global variables? You should be using lexical variables, declared with my, everyhere you can. For example, you can declare the loop variable inside the for statement.
    foreach my $item (@array) {

    I don't like the style of declaring lexical variables at the top of a function. I much prefer declaring the variable where it is first assigned. It must be a carryover from C where that is the only way to declare variables. But I can understand it.

Log In?
Username:
Password:

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

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

    No recent polls found