Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Help with arrays

by perlguru22 (Acolyte)
on Sep 22, 2012 at 03:57 UTC ( #995029=perlquestion: print w/ replies, xml ) Need Help??
perlguru22 has asked for the wisdom of the Perl Monks concerning the following question:

Hey guys I am taking an intro to scripting languages and we are using perl but I seem to be stuck in this problem. "Find the average of the numbers in an array (@nums) of unknown length. I know it starts something like this @nums = (); But I don't know where to go from there. I was hoping someone could guide me. Thanks

Comment on Help with arrays
Re: Help with arrays
by 2teez (Priest) on Sep 22, 2012 at 04:19 UTC

    I know it starts something like this @nums = (); But I don't know where to go from there
    You probabily, might have to check your course material again on array. However, let me show a trival example, that may help.

    use warnings; use strict; my @nums = 1 .. 10; my $sum = 0; foreach my $index ( 0 .. $#nums ) { $sum += $nums[$index]; } print "Average: ", $nums[0], " to ", $nums[$#nums], " = ", $sum / scal +ar @nums;

    Average: 1 to 10 = 5.5
    As shown above, $#nums is used to get the last index of an array.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
      What I am having trouble understanding is how to make an array with an uknown length? I don't understand how that works sorry I am not trying to be complicated thanks =)
        I had this so far
        #!/usr/bin/perl @nums = (); for(@nums) { $sum += $_; } $size = @nums; $average = $sum / $size; print "$average";
        It works when I put elements in the @nums but I am just confused on the unknown length part.

        You can use shift operator in this case..

        shift operator takes an array, removes an element from the start and updates the existing array

        If your array becomes empty, it returns undef, which you can handle

        sub average { $sum = shift @_; while (defined($num = shift @_)) { $sum += $num; } }


        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.

Re: Help with arrays
by Kenosis (Priest) on Sep 22, 2012 at 06:01 UTC

    What I am having trouble understanding is how to make an array with an uknown length?

    It's common to have to work with an array without knowing its length--in Perl or other computer languages. Consider the following:

    use strict; use warnings; my @array = qw/5 8 2 78 5 1 9 9 16/; # Example 1 for my $number (@array) { print $number, "\n"; } # Example 2 print "\n", 'Number of elements in @array: ', scalar @array; # Example 3 print "\n\n", 'Number of elements in @array: ', $#array + 1, "\n\n"; # Example 4 for ( my $i = 0 ; $i < @array ; $i++ ) { print $array[$i], "\n"; } # Example 5 my $total; for my $number (@array) { $total += $number; } print "\n", '$total is: ', $total;

    First, notice the following at the top of the script:

    use strict; use warnings;

    Always have these, as they'll preemptively catch issues in your scripts, potentially saving your hours of headaches. (Omit them, however, if you prefer these headaches... :)

    All the Examples could be working with an array of an unknown length. It just so happens that we know the length, since we've initialized it.

    Example 1 iterates through each element of @array, assigning $number an each element's value that's then printed within the loop. Examples 2 & 3 show the number of elements in @array:

    Number of elements in @array: 9

    Example 4 shows a more traditional C-style for loop, and produces the same output as Example 1:

    5 8 2 78 5 1 9 9 16

    Example 5 shows one way to get the sum of the numbers in @array, and here's its output:

    $total is: 133

    Perhaps the above will assist you with how to "Find the average of the numbers in an array (@nums) of unknown length."

    Hope this helps!

      I think I Finally figured it out =)
      #!/usr/bin/perl use warnings; $sum = 0; @nums = (); push (@nums,(4,4)); $sum += $_ for @nums; $size = @nums; $average = $sum / $size; print "$average";
      This worked I am not sure if it's the correct way but it gave me the average

        Yes--well done!

        ...I am not sure if it's the correct way...

        Tim Toady!

        If I may, however, offer the following for you to consider:

        #!/usr/bin/perl use strict; use warnings; my $sum = 0; my @nums = (); push( @nums, ( 4, 8 ) ); $sum += $_ for @nums; my $size = @nums; my $average = $sum / $size; print "$average";

        My the above message.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://995029]
Approved by Athanasius
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: (4)
As of 2014-08-01 02:56 GMT
Find Nodes?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:

    Results (256 votes), past polls