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

consider this:
@arr = qw~0~; $foo = \@arr; @{$foo} ? print "TRUE\n" : print "FALSE\n"; # deref 1 $foo->[0] ? print "TRUE\n" : print "FALSE\n"; # defef 2
Why is this not the same to perl? is this a legitmate bug?

Replies are listed 'Best First'.
Re: Arefs: Testing for Truth:
by jZed (Prior) on Mar 24, 2004 at 00:27 UTC
    Your first one tests for scalar @$foo and is true because @$foo contains 1 element. Your second test is for the value of the first element of the array which is 0, or false.
Re: Arefs: Testing for Truth:
by Limbic~Region (Chancellor) on Mar 24, 2004 at 00:29 UTC
    Anonymous Monk,
    I think this is just your misunderstanding.
    • An array in scalar context will return the number of elements : 1 = true
    • An array element in scalar context will be the value of that element : 0 = false
    If this still didn't make sense you should check out What is Truth in the tutorials section.

    Cheers - L~R

Re: Arefs: Testing for Truth:
by Vautrin (Hermit) on Mar 24, 2004 at 00:43 UTC

    An array in boolean context is assumed to mean "are there any elements in me" and represents true because it contains 0. Since undefined values, the string "", and 0 (also "0") are false, the 0th element in the array is false.

    (defined $foo->[0]) ? print "TRUE\n" : print "FALSE\n";

    Should print TRUE. Note that you should use:

    use strict; use warnings;

    at the top of all your scripts to alert you to things like this in your code. Of course, in this particular instance, there would be no warnings because what you did is supposed to be widely known.


    Want to support the EFF and FSF by buying cool stuff? Click here.
•Re: Arefs: Testing for Truth:
by merlyn (Sage) on Mar 24, 2004 at 00:29 UTC
    Eh? Where's the bug? In the first case, you're seeing if the length is true, and it is (there's one element). In the second case, you're testing the truth of the first element of the array (it's 0), and it's false.

    What did you think you were doing instead?

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Testing for Truth
by Happy-the-monk (Canon) on Mar 24, 2004 at 00:34 UTC

    The first tests for elements in the array. There are elements (there's one) in it, hence it is tested true.
    The second tests the first element for truth. It is a "0", hence it's tested false.