http://qs321.pair.com?node_id=163546

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.