Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re^3: Help with arrays

by roboticus (Chancellor)
on Sep 22, 2012 at 12:58 UTC ( #995101=note: print w/replies, xml ) Need Help??

in reply to Re^2: Help with arrays
in thread Help with arrays


The phrase "unknown length" simply means that you (the programmer) don't know how long the array is beforehand. The intent is to make you think of a way to accomplish the task that particular bit of information. Perl, however, will always know how many items are in the array. If you build that kind of knowledge into your code, you make your code less easy to reuse.

For example:

sub sum_5 { # Returns the sum of array elements. # ...if your array happens to contain 5 items... my @array = @_; my $sum=0; # The programmer assume the array length right here: # v for my $i (0 .. 4) { $sum += $array[$i]; } return $sum; } sub sum_array { # Return the sum of all array elements my @array=@_; # The programmer asks the array how long it is here: vvvvvvv for my $i (0 .. $#array) { $sum += $array[$i]; } } my @a1 = (1,2,3,4,5); my @a2 = (1,2,3,4,5,6,7,8,9,10); print "** sum_5 **\n"; print "Sum of array 1 is ", sum_5(@a1), "\n"; print "Sum of array 2 is ", sum_5(@a2), "\n"; print "** sum_array **\n"; print "Sum of array 1 is ", sum_all(@a1), "\n"; print "Sum of array 2 is ", sum_all(@a2), "\n";

As you can see, the difference between the subroutines is that in the first one, the programmer assumes that all arrays it will be used with have exactly 5 elements. In the second example, the programmer instead asks the array how long it is.


  • I didn't test the example code, so it likely has a bug or two.
  • This isn't the most "perlish" way of adding things up. There are better ways, but this seemed the most clear way of showing the difference between the two cases.
  • Strictly speaking, $#array doesn't tell you how long the array is, it tells you the index of the last element in it. Since perl indexes arrays using 0-based numbers, it's one less than the number of items in the array.


When your only tool is a hammer, all problems look like your thumb.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://995101]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2018-04-26 04:59 GMT
Find Nodes?
    Voting Booth?