Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: array testing

by erasei (Pilgrim)
on Oct 30, 2003 at 15:31 UTC ( [id://303280]=note: print w/replies, xml ) Need Help??


in reply to array testing

You want to use the 'defined' function to test if your array contains anything. 'defined' will return true if the array has any elements, and will return false if it is A: not defined at all, or B: defined null (@arr = () returns false).
my @one = ('A', 'B', 'C'); my @two = (); if (defined(@one)) { print "Array one is defined.\n"; } if (defined(@two)) { print "Array two is defined.\n"; }
will print only:
Array one is defined.

Replies are listed 'Best First'.
Re: Re: array testing
by Roy Johnson (Monsignor) on Oct 30, 2003 at 17:06 UTC
    You should only use defined on scalars.
    perldoc -f defined says:
    Use of "defined" on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behavior may disappear in future versions of Perl. You should instead use a simple test for size:
    if (@an_array) { print "has array elements\n" } if (%a_hash) { print "has hash members\n" }
Re: Re: array testing
by chromatic (Archbishop) on Oct 30, 2003 at 17:10 UTC

    perldoc -f defined for 5.8.1 (and earlier, I believe) lists defined as deprecated for aggregates. Besides that, an array in scalar context returns the number of elements. Just do:

    if (@one) { ... }
Re: Re: array testing
by bart (Canon) on Oct 31, 2003 at 02:21 UTC
    You want to use the 'defined' function to test if your array contains anything.
    I don't think so. See this code modified from yours:
    @three = (1); @three = (); if (defined(@three)) { print "Array three is defined.\n"; }
    which prints:
    Array three is defined.
    
    (perl 5.6.1)

    This is the reason why using defined in aggregates (= arrays and hashes) is deprecated. Quoting from perlfunc:

    Use of "defined" on aggregates (hashes and arrays) is deprecated. It used to report whether memory for that aggregate has ever been allocated. This behavior may disappear in future versions of Perl.
    That's what you're seeing here: array @three has been used, and hasn't completely been freed. A useless test, this "defined(@array)", if you ask me.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-25 05:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found