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

Helloo there monks, a trifle too much wine at this end, as is often the case :) However, my question be :

How can one find out if an array is empty or not ?

Something like :
my @array=glob('path/*');

This is jAust an example.

if($#array==0){ print "this doesn't werk anyway you doughnut.\n"; }
My brain is no0t functioning as it should, so someone elses quota would be mostly appriciated. thanks.

Replies are listed 'Best First'.
Re: Empty or not empty ?
by ikegami (Patriarch) on Dec 15, 2006 at 02:14 UTC

    $#array returns the index of the last element in @array (not the number of elements in @array).
    If @array has 2 elements, $#array returns 1* (because the elements are numbered 0 and 1*).
    If @array has 1 element, $#array returns 0*.
    If @array has no elements, $#array returns -1*.

    In scalar context, @array returns the number of elements in @array.
    If @array has 2 elements, @array returns 2.
    If @array has 1 element, @array returns 1.
    If @array has no elements, @array returns 0.

    So use
    if ($#array == -1), or
    if (@array == 0), or
    if (!@array)

    * — That's assuming $[ has been left unchanged. Changing $[ is highly discouraged.

Re: Empty or not empty ?
by revdiablo (Prior) on Dec 15, 2006 at 02:08 UTC

    Simply:

    if (@array) {}

    Update: oops! Thanks to ikegami for pointing out that I negated the logic here. That could be if (!@array) {} as others have written.

Re: Empty or not empty ?
by pemungkah (Priest) on Dec 15, 2006 at 05:56 UTC
    Too much wine indeed! Just use the array in scalar context:
    if (! @array) { print "nothing there\n"; }
Re: Empty or not empty ?
by jesuashok (Curate) on Dec 15, 2006 at 02:10 UTC
    use strict; my @array = (); print "Array is empty\n" if ( ! @array );