1
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?

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • 3
    1) This code does not compile: there is a missing `}` (the one that should close the foreach loop). 2) What are you trying to do? – Dada Jun 14 '22 at 10:30

1 Answers1

2

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/@_;
}
ikegami
  • 367,544
  • 15
  • 269
  • 518