Home > Back-end >  why can't I work with (@_) directly and why does creating $item not pass the passed values as s
why can't I work with (@_) directly and why does creating $item not pass the passed values as s

Time:06-16

sub average {
    my $uebergeben = (@_);
    my $verrechnen = 0; 
    
    foreach my $item (@_){
        $verrechnen  = $item;
    }

    my $scalardef = $verrechnen;
    my $average = $scalardef/$uebergeben;
    print "$average\n";
}

my @array = 20;
my @hallo = 10;

average(@array,@hallo);

Why does the variable $verrechnen have to be created outside the foreach loop?

Why is $verrechnen = (@_) not possible and why is $item not in scalar context?

CodePudding user response:

Why does the variable $verrechnen have to be created outside the foreach loop?

Because you want it to exist longer than a pass of the loop.


Why is $verrechnen = (@_) not possible

This is perfectly valid syntax.

Evaluating an array in scalar context returns the number of elements in it, so this adds the number of elements in @_ to $verrechnen.

For example, if you pass four arguments, @_ will have four elements, and $verrechnen = (@_) will add four to $verrechnen.

Of course, that's not what you want to do here.


why is $item not in scalar context?

Why would you even ask that? $item is not context-sensitive. It does exactly the same thing in scalar context, list context and void context.

Anyway, $item is used twice.

The idea of context doesn't make much sense for for my $item (since it's not in an expression), so let's ignore this use.

The other use is in $verrechnen = $item;, where $item is evaluated in scalar context as per Scalar vs List Assignment Operator.


Simplified:

sub average {
    my $sum = 0;
    $sum  = $_ for @_;
    return $sum/@_;
}
  • Related