in reply to Printing the length of an array ?

or, perhaps canonically, but definitely NOT canonically (see FunkyMonk's below),
#! /usr/bin/perl use strict; use warnings; my @array = qw/1 2 3 4 5 6 7/; print "number of elements is " . ++$#array . "\n";

The increment is necessary because the first element is @array[0].

This produces:

ww@GIG:~/pl_test$ perl elementsinarray.pl number of elements is 7

Replies are listed 'Best First'.
Re^2: Printing the length of an array ?
by FunkyMonk (Bishop) on Mar 30, 2008 at 21:21 UTC
    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 ];

      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;