Home > database >  Average value function returning random number on empty array
Average value function returning random number on empty array

Time:10-12

I'm using perl 5.16.

I have the following function to give me the average value inside any given array:

sub GetAvgValue {
    my @Array = @_;

    my $Sum = 0;
    foreach my $CurVal (@Array) {
        $Sum  = $CurVal;
    }

    if ( scalar(@Array) ) {
        return $Sum / scalar(@Array);
    }
    else {
        return undef;
    }
}

I want it to return undef when there are no elements inside the array, but instead it returns a random-looking integer:

print Dumper GetAvgValue([]);
# 1. iteration: $VAR1 = '42311136';
# 2. iteration: $VAR1 = '38006240';
# 3. iteration: $VAR1 = '39394784';

CodePudding user response:

[] is an array reference. You are not using array references in your code. This sub call is therefore wrong:

GetAvgValue([]);

The argument list @_ is now not empty, it contains one value: an array reference. What you should do is:

GetAvgValue();

Send an empty list. Because you assign the array inside the subroutine like this:

my @Array = @_;

If you were using an array reference like [] is, you would be doing this:

my $aref = shift;         # or
my $aref = $_[0];         # or
my ($aref, @rest) = @_;   # etc

my @Array = @$aref;       # dereference 

The "random looking value" at the end is the numeric address of the array reference, subjected to a division by 1. Demonstration:

$ perl -lwe'print []'
ARRAY(0x79a7d0)

$ perl -lwe'print []/1'
15443920
  •  Tags:  
  • perl
  • Related