*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! |