But this doesn't change the size of @array. To do this, you can use $#array = 0;
...is incorrect advice.
Per the Camel book: "Assigning to $#array changes the length of the array." So in that respect you are accurate. However, $#array is the subscript of the last element of @array. Zero is the first element of any array, unless you've messed with $[ (which you shouldn't have). So assigning zero to $#array will turn it into a one-element array, it won't erase that last element, $array[0].
Also per the Camel book: "You can truncate an array down to nothing by assigning the null list to it. The following two examples are equivalent: @whatever = (); or $#whatever = -1;"
So to reiterate, the following examples will both empty out an array:
@array = (); $#array = -1;
It's up to you to decide which is easier to read.
Regarding the other suggestion of @array = map { undef } @array;, that will work if your intention is to undefine the value of each element of the array, but leave the array as large as it was in the first place. If you intend to put stuff into the array again, and it's likely to grow to be as big as it was before, leaving it large will offer a slight speed improvement (similar to pre-extending an array by saying, $#array = 999;, which creates a pre-extended but empty array of 1000 elements. Of course this speed improvement comes at the cost of the overhead required to hold onto 1000 empty elements.
But if your intent is to shrink the size of the array altogether, and not retain the undef elements, you should use the @array = (), or $#array = -1 construct.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
In reply to Re: Re: Answer: How do I completely empty out an array?
by davido
in thread How do I completely empty out an array?
by vroom
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |