in reply to Check if array is null

Texan,

Cheers - L~R

Replies are listed 'Best First'.
Re^2: Check if array is null
by Anonymous Monk on Oct 06, 2004 at 15:28 UTC
    perldoc -f defined
    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"   }
      Anonymous Monk,
      Thanks for another example of the importance of learning to fish - RTFMing. It also points out that no matter how good of a fisherman we think we are - there is always more to learn.

      Cheers - L~R

Re^2: Check if array is null
by ikegami (Patriarch) on Oct 06, 2004 at 16:01 UTC

    Your first and second are identical in function:

    our @array2; my @array3; my @array4 = (); my @array5 = (undef); my @array6 = ('one'); print("defined:\n"); print('array1: ', defined(@array1)?1:0, "\n"); # 0 print('array2: ', defined(@array2)?1:0, "\n"); # 0 print('array3: ', defined(@array3)?1:0, "\n"); # 0 print('array4: ', defined(@array4)?1:0, "\n"); # 0 print('array5: ', defined(@array5)?1:0, "\n"); # 1 print('array6: ', defined(@array6)?1:0, "\n"); # 1 print("\n"); print("explicit scalar:\n"); print('array1: ', scalar(@array1)?1:0, "\n"); # 0 print('array2: ', scalar(@array2)?1:0, "\n"); # 0 print('array3: ', scalar(@array3)?1:0, "\n"); # 0 print('array4: ', scalar(@array4)?1:0, "\n"); # 0 print('array5: ', scalar(@array5)?1:0, "\n"); # 1 print('array6: ', scalar(@array6)?1:0, "\n"); # 1 print("\n"); print("implicit scalar:\n"); print('array1: ', @array1?1:0, "\n"); # 0 print('array2: ', @array2?1:0, "\n"); # 0 print('array3: ', @array3?1:0, "\n"); # 0 print('array4: ', @array4?1:0, "\n"); # 0 print('array5: ', @array5?1:0, "\n"); # 1 print('array6: ', @array6?1:0, "\n"); # 1 print("\n");

    I don't think defined should be used on an array.

      ikegami,
      Your first and second are identical in function

      Not according to my test:

      #!/usr/bin/perl use strict; use warnings; my @array = (undef, undef); print "foo\n" if defined @array; print "bar\n" if grep defined , @array; __END__ $ perl foo.pl defined(@array) is deprecated at foo.pl line 5. (Maybe you should just omit the defined()?) foo $ perl -v This is perl, v5.8.5 built for cygwin-thread-multi-64int

      Cheers - L~R

        Read again. I said the first and second are the same, not the first and third. Your snippet even supports me because it says defined shouldn't be used on arrays.