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

Hi , I have stored some values in an array and used in my program. After a while I want to initialize entire array with either blank or zeros. Is there any function to initiate an array? Thanks Ashok

Replies are listed 'Best First'.
Re: array initialization
by Dominus (Parson) on Nov 13, 2000 at 09:11 UTC
    To fill an array with zeroes, use:

    @a = (0) x 143; # 143 zeroes
    Or if the array already has the length you want, and you want to make every element zero, use:
    @a = (0) x @a; # every element set to zero
    But often, the best thing to do is just destroy what's in the array:

    undef @a;
    If you undefine the array, and then try to look at the elements, they will be undefined, and an undefined array element behaves like 0 if you use it as a number. For example:

    undef @a; $z = $a[3] + 12; print $z;
    This prints 12.

Re: array initialization
by merlyn (Sage) on Nov 13, 2000 at 18:02 UTC
(tye)Re: array initialization
by tye (Sage) on Nov 14, 2000 at 01:35 UTC

    Note I tend to "clear" an array using:

    @a= ();
    and not with:
    undef @a;

    The difference is that undef @a will free the memory allocated for the array. If you have put a really huge number of elements into @a and don't plan on doing that again for quite a while, then you probably do want to use undef @a to allow that memory to be reused in the mean time. Otherwise, @a= () is probably a better choice as it removes the overhead of freeing and then later reallocating memory.

    Also note that @a= () does free the memory allocated for the elements of the array (except for elements that have other references to them).

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