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

How to empty an array ???
when an array is used earlier in the program and if it is be
reset, what shud I do ??
For examples
the array is
 @flowers

Replies are listed 'Best First'.
Re: How to empty an array ???
by GrandFather (Saint) on Nov 25, 2005 at 22:00 UTC
    @flowers = ();

    DWIM is Perl's answer to Gödel
Re: How to empty an array ???
by marto (Cardinal) on Nov 25, 2005 at 21:59 UTC
Re: How to empty an array ???
by Albannach (Monsignor) on Nov 25, 2005 at 22:31 UTC
    Taking another approach, depending on the requirements of your algorithm you might just confine your @flowers in blocks using my like so:
    use strict; my @flowers; { my @flowers = qw(rose daisy buttercup); # arrange your flowers here } print @flowers; # prints nothing as these flowers were never assigned
    Mind you, from a readability point of view, re-use of variable names is not generally a good idea in my opinion, as it can be quite confusing to others unless your array is always used for the same purpose (e.g. as working space for some subroutine).

    --
    I'd like to be able to assign to an luser

Re: How to empty an array ???
by bart (Canon) on Nov 25, 2005 at 22:54 UTC
    I agree with Albannach: you should learn about variable scopes.

    In perl, there typically never is a need to empty an array. If you limit the scope of your array to the loop block, you'll simply get a new empty array every time through the loop. Simple, effective, and very generically appliable.

    for (1 .. 3) { my @flowers; # new, emtpy array, every time ... }
      In perl, there typically never is a need to empty an array.
      Except, when you're running low on memory. Explicitly using an undef @flowers might help you in that case even if the array goes out of scope and most of its memory would get reclaimed anyway.

      But usually, using the right scope for variable declaration is enough.

Re: How to empty an array ???
by ikegami (Patriarch) on Nov 25, 2005 at 22:07 UTC

    and
    $#flowers = -1;

    and
    splice(@flowers, 0, @flowers);

    and
    splice(@flowers, -@flowers);

      and (I'm sure there are more)

      shift @flowers while @flowers;
A reply falls below the community's threshold of quality. You may see it by logging in.