Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: array check help

by DigitalKitty (Parson)
on May 16, 2003 at 20:00 UTC ( [id://258751]=note: print w/replies, xml ) Need Help??


in reply to array check help

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.

Replies are listed 'Best First'.
Re: Re: array check help
by Limbic~Region (Chancellor) on May 16, 2003 at 20:29 UTC
    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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://258751]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-25 08:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found