Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^3: Help with arrays

by roboticus (Canon)
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

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:

  • 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.

...roboticus

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


Comment on Re^3: Help with arrays
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://995101]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (16)
As of 2014-09-30 17:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (378 votes), past polls