pglenski has asked for the wisdom of the Perl Monks concerning the following question:

What's the difference (if any) between @tmp=() and undef @tmp? Don't they do the same thing?

2006-02-25 Retitled by Corion, as per Monastery guidelines
Original title: 'Array'

Replies are listed 'Best First'.
Re: how to clear an array
by bart (Canon) on Feb 25, 2006 at 01:00 UTC
    They do not do the same thing, but it's not worth it to worry about it. The difference is tiny.

    @temp = (); only empties the array, undef @temp; completely removes it from memory. For the latter, the final memory consumption will be ever so slightly less. If you want to use the array again, the former will be just a teeny weeny little bit faster.

    But like I said, don't break your head over it. The difference is negligible.

Re: how to clear an array
by HollyKing (Pilgrim) on Feb 24, 2006 at 23:10 UTC

    @tmp = () makes @tmp an array with zero elements. undef @tmp undefines @tmp. Check the output from:

    my @foo = qw(foo bar baz); @foo = (); print "\@foo is defined.\n" if defined @foo; my @bar = qw(foo bar baz); undef @bar; print "\@bar is defined.\n" if defined @bar;

    Owl looked at him, and wondered whether to push him off the tree; but, feeling that he could always do it afterwards, he tried once more to find out what they were talking about.

      That may work fine on Perl4 but:
      perldoc -f defined [snip] Use of "defined" on aggregates (hashes and arrays) is deprecated +.
      So don't do that. :-)

        I wouldn't use something like that in production code, but it's good to know that there's a reason beyond my personality flaws. ;)

        Owl looked at him, and wondered whether to push him off the tree; but, feeling that he could always do it afterwards, he tried once more to find out what they were talking about.