in reply to using undef on a array

The usual way to use undef on an array is like this:

@_ = (1,2,3); @_ = (); # this will empty array but this will undef @_; # empty array and allow reallocation memory print @_;

Both lines shown remove all the values from @_. Underneath @_ = (); calls the C code void av_clear(AV*); whereas undef @_ calls void av_undef(AV*);

The underlying C functions differ in that in the first case memory remains allocated for the array so if you just want to empty it so you can fill it again this is the way to go. In the second case memory should be deallocated and garbage collected. If you undef an array and then go to use it again you encounter the overhead involved with setting up any new array. There is a note somewhere in the docs(can't find it) noting that using undef to empty an array is inefficient compared to setting it to ()

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
(tye)Re: using undef on a array
by tye (Sage) on Oct 31, 2001 at 20:22 UTC

    This is the most accurate answer so far, IMO. I'd like to add some fairly minor points of clarification. The memory being free()d by undef @a is only the memory that the array itself uses to keep track of its elements. The memory allocated for the elements is free()d even when you just do @a= () (unless there are other references to elements elsewhere, in which case undef @a won't free that memory either).

    So the only time that it makes sense to undef @a is if @a previously contained a very large number of elements and you don't expect that it will again for a long time.

    Also, $#a= -1 is just an obfuscated way of writing @a= (), so please use the latter.

    Using defined on aggregates (arrays and hashes) is generally a very bad idea. Please don't do that unless you have very strange requirements and a good understanding of Perl internals.

            - tye (but my friends call me "Tye")