vroom has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How do I find the size of an array?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I find the size of an array?
by davorg (Chancellor) on Jun 13, 2000 at 14:33 UTC
    The "value" of an array variable in any scalar context is its length. E.g.
    scalar(@array)
    Or
    $length = @array;
      Either of the commands should do the job: scalar(@array); $#array Shashidhar Iddamsetty
        wrong
Re: How do I find the size of an array?
by panda.umesh9 (Initiate) on Feb 09, 2010 at 17:55 UTC
    $length=($#array+1)
      $#array + 1 is wrong. $#array is the index of the last element in @array. It is *normally* one less than the number of elements in the array, but not always, as it assumes that array indices start at 0. If $[ is set then that is not necessarily the case.

      What's wrong with:

      $length = @array;

      For example:

      #!/usr/bin/perl use strict; my @array = qw(one two three); my $length = $#array + 1; print "Dollar pound array = $length\n"; $length = @array; print "At symbol array = $length\n"; __DATA__ {C} > test.pl Dollar pound array = 3 At symbol array = 3
        What's wrong with:
        $length = @array;
        Nothing. TIMTOWTDI.

        -- Randal L. Schwartz, Perl hacker

        The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.