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!


In reply to Re: Help with arrays by Kenosis
in thread Help with arrays by perlguru22

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.