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

Hello perl monks, I have an array @NotFound , how can i check if that array is empty or not, please do provide me some help Thank you very much

Replies are listed 'Best First'.
Re: array check help
by The Mad Hatter (Priest) on May 16, 2003 at 19:20 UTC
    A simple negated if test will do...
    print "empty" if !@NotFound;

      I like code that reads well. I was going to say print "empty" if not @NotFound but realized it's finally a good reason to use the unless keyword.

      print "empty" unless @NotFound;

      --
      [ e d @ h a l l e y . c c ]

Re: array check help
by DigitalKitty (Parson) on May 16, 2003 at 20:00 UTC
    Hi Anonymous Monk,

    The easiest method to determine if an array is empty is to analyze the value it 'equates' to ( true or false ).

    #!/usr/bin/perl -w use strict; my @array = qw( Bob Carol Mike Katie ); if( @array ) { print "\@array is not empty!\n"; } else { print "\@array is empty!\n"; }


    The line if( @array ) is essentially saying 'if the array has a true value'...if it were empty, it would equal false.
    You can delete all the elements of an array of by assigning a empty list to it:

    #!/usr/bin/perl -w use strict; my @array = qw( Bob Carol Mike Katie ); # Delete the contents of the array. @array = (); if( @array ) { print "\@array is not empty!\n"; } else { print "\@array is empty!\n"; }


    Hope this helps,
    -Katie.
      DigitalKitty,
      While this is on the money, it might be useful to indicate why an empty array is false and a non-empty array is true. The "What is Truth" tutorial has some good information.

      An array in this context will return the number of elements in the array. For purposes of truth, anything that equates to a non-zero value or an empty string is considered true. Even if the array had one element that was undef - it would be true. I think it really depends on what the OP meant by empty. I have seen a lot of people new to Perl think that because there are only undef elements, it is empty. While this is not true (pun intended), an alternative solution needs to be provided for this possibility of misunderstanding. This could be solved with this monstrosity:

      (grep defined, @array) ? print "It has at least one non-undefined elem +ent\n" : print "It is effectively empty\n";

      Cheers - L~R

Re: array check help
by dorko (Prior) on May 16, 2003 at 19:21 UTC