Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

undef vs. $foo = 0

by DaWolf (Curate)
on May 02, 2002 at 14:34 UTC ( [id://163546]=perlquestion: print w/replies, xml ) Need Help??

DaWolf has asked for the wisdom of the Perl Monks concerning the following question: (input and output)

Wich one is the best way to reset a variable?

1st method:
foreach $foo(@foo) { undef $bar; ... $bar = $some + $thing; }
2nd method:
foreach $foo(@foo) { $bar = 0; ... $bar = $some + $thing; }
TIA, DaWolf

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: undef vs. $foo = 0
by ariels (Curate) on May 02, 2002 at 14:39 UTC
    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".

Re: undef vs. $foo = 0
by crazyinsomniac (Prior) on May 03, 2002 at 05:11 UTC
    The best method is
    foreach $foo(@foo) { $bar = $some + $thing; }
    no need for an intermediary step unless you're doing something with $bar.

    If $bar has a default value, set it to that value, otherwise undef.

Re: undef vs. $foo = 0
by Mur (Pilgrim) on May 06, 2002 at 14:29 UTC
    undef $bar may have some useful side-effects, if $bar is an object.
    $bar = Foo->new(); ... undef $bar;
    will invoke "Foo::DESTROY", if it is defined.
    $bar = 0;
    will also invoke DESTROY, but not if '0' is a valid assignment in the "Foo" class (long shot, I know).
Re: undef vs. $foo = 0
by Mur (Pilgrim) on May 06, 2002 at 14:58 UTC
    undef $bar may have some useful side-effects, if $bar is an object.
    $bar = Foo->new(); ... undef $bar;
    will invoke "Foo::DESTROY", if it is defined.
    $bar = 0;
    will also invoke DESTROY, but not if '0' is a valid assignment in the "Foo" class (long shot, I know).

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-03-29 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found