in reply to Re: Printing the length of an array ?
in thread Printing the length of an array ?

The ++ makes the array one element longer, adding an undef at the end:
my @array = qw/1 2 3 4 5 6 7/; print "number of elements is " . ++$#array . "\n"; print Dumper \@array;

number of elements is 7 $VAR1 = [ '1', '2', '3', '4', '5', '6', '7', undef ];

Replies are listed 'Best First'.
Re^3: Printing the length of an array ?
by ww (Archbishop) on Mar 30, 2008 at 21:30 UTC
    Correct!

    Better, and clearer, to write for line 7:

    my $count = $#array; print "number of elements is " . ++$count . "\n";

      That can be wrong for at least one very bad reason that you should be glad you don't know. This code is always correct, shorter, and less noisy:

      my $count = @array;
        That can be wrong for at least one very bad reason that you should be glad you don't know.

        That's so chromatic... and, of course, it does induce a post asking: what bad reason?

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
        oooooh, but i want to know