You can do any of these things: assign an empty list to the
array, undef it or assign -1 to its "last index value".
@array=();
undef @array;
$#array = -1;
$#array = -1 was originally contrbuted by Benne -- Ed. | [reply] [Watch: Dir/Any] [d/l] |
| [reply] [Watch: Dir/Any] [d/l] [select] |
splice( @array );
| [reply] [Watch: Dir/Any] [d/l] |
| [reply] [Watch: Dir/Any] |
@array = map { undef } @array;
| [reply] [Watch: Dir/Any] [d/l] |
But this doesn't change the size of @array. To do this,
you can use $#array = 0;.
daniel.
Update: Oops, this is wrong (thanks to davido
for pointing this out). Correct is $#array = -1;.
| [reply] [Watch: Dir/Any] |
In the context of "How do I completely empty out an array", your solution,
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 | [reply] [Watch: Dir/Any] [d/l] [select] |
~~(;#>_<#;)~~
My mistake, you are right, it does not work, it will only replace all the entries of the array with undef's and the array size will remain the same. Just another of my stupid mistakes!
| [reply] [Watch: Dir/Any] |