Returned variable without reference in the source code

(I recently decided to learn Perl using the 6th edition of O'Reilly Learning Perl).

Purpose: Make a list of numbers from another list that only includes numbers that are greater than the average of the original array. However

This was provided in the book.

my @fred = above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";

my @barney = above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";

      

This is my answer.

sub total {
    #computes total of array
}
sub average {
    #computers average from
    #array and length of said array
}

sub above_average {
    $average = average(@_);
    my @ab_avr;
    foreach $num (@_) {
        if ($num > $average) {
            push @ab_avr, $num;
        }
    }
    @ab_avr;
}

      

The first sample seems to work, however the second example outputs 100 which is correct, but I don't understand why 100 is returned at all. The array I passed in above_average()

was only a number between 1 and 10, with an optional parameter of 100. Assuming the default $ _ variable is never used, why is 100 shown?

Thank.

+3


source to share


1 answer


Lists and arrays are subtly different . You cannot pass an array to a routine; all subroutines accept lists and return lists; the entire list that is passed is available in the subroutine as if it were an array @_

.

In this case you are passing through 100, 1..10

, so it @_

will contain 100, 1, 2, 3, ..., 10.



This is not really a problem in your code, but you should try to always use lexical words where possible, eg. my $average =

, foreach my $num

and use strict warnings and warnings.

+2


source







All Articles