Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Answer: undef vs. $foo = 0

( #163548=categorized answer: print w/ replies, xml ) Need Help??

Q&A > input and output > undef vs. $foo = 0 contributed by ariels

One sets the variable to undef, the other to 0. They're not equivalent. "Resetting" a variable is probably more like undef $bar.

But which you want probably depends on what it is you want to do. For some applications, you'd set $bar=0 initially (or $bar='' for others), so that could be useful.

Example

To print the sum of the numbers in an array,
my $sum; # ... $sum = 0; $sum += $_ for @array; print "Sum is $sum\n";
Using undef $sum would be a somewhat subtle error in this case.

Other times, you want undefinedness, and you undef things accordingly. Which is right to use depends on what is "right".

Comment on Answer: undef vs. $foo = 0
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2015-07-05 04:29 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 (60 votes), past polls