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


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

perlguru22:

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.

Notes:

...roboticus

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