http://www.perlmonks.org?node_id=822246


in reply to How do I find the size of an array?

$length=($#array+1)
  • Comment on Re: How do I find the size of an array?

Replies are listed 'Best First'.
Re: Answer: How do I find the size of an array?
by DrHyde (Prior) on Feb 10, 2010 at 11:00 UTC
    $#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.
Re: Answer: How do I find the size of an array?
by VinsWorldcom (Prior) on Feb 09, 2010 at 21:02 UTC

    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.