Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: To initialise or not to initialise?

by bradcathey (Prior)
on Jun 24, 2004 at 11:48 UTC ( #369295=note: print w/replies, xml ) Need Help??


in reply to To initialise or not to initialise?

kiat, another good question, one that I have thought about often. Here's where I'm at now. I no longer initialize with a value, unless that value is to be used immediately and/or it helps me read what I'm doing:
my $ctr = 0; for ( 0 .. 5 ) { if ($foo[$_] eq $bar) { $ctr++; } }
I have found there is a difference between:
my $variable;
and
my $variable = "";
or
my $variable = 0;
depending on usage. In summary, I don't think there can be a hard a fast rule. Like many things, it depends on context and the readibility you need.

—Brad
"Don't ever take a fence down until you know the reason it was put up. " G. K. Chesterton

Replies are listed 'Best First'.
Re^2: To initialise or not to initialise?
by kiat (Vicar) on Jun 24, 2004 at 13:30 UTC
    Hi bradcathey,
    I have found there is a difference between:
    Do you mean the difference between being defined and undefined?
    my $var1; # not printed because $var1 is not defined print "var1: $var1\n" if defined $var1; my $var2 = ''; # printed with $var2 as an empty string # output var2: print "var2: $var2\n" if defined $var2; my $var3 = 0; # printed with $var3 set to 0 # output var3: 0 print "var3: $var3\n" if defined $var3;
    cheers,
      Precisely, thanks for clearing up the terminology. And I have to apologize for not being about to think of a good example, but I have found at times I need the undefined variable, as opposed to the defined, inferring a value.

      —Brad
      "Don't ever take a fence down until you know the reason it was put up. " G. K. Chesterton
        Ah okay.

        I thought it might be something to do with concatenation at first, which also shows a subtle difference:

        my $var1; print $var1 .= 'r', "\n"; # prints r my $var2 = ''; print $var2 .= 'r', "\n"; #prints r my $var3 = 0; print $var3 .= 'r', "\n"; #prints 0r
        :)

Log In?
Username:
Password:

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

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







    Results (89 votes). Check out past polls.

    Notices?