Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: resetting a foreach loop!

by pryrt (Abbot)
on Nov 16, 2017 at 22:13 UTC ( [id://1203627]=note: print w/replies, xml ) Need Help??


in reply to resetting a foreach loop!

Change average() to use its parameters, not the top-level @array directly; then you can limit @array to the appropriate context:

sub average { if (@_) { my @temp = @_; my $sum = 0; foreach (@temp) { $sum = $sum + $_; } return $sum/@temp; } }

edit: fixed indenting for readability

Replies are listed 'Best First'.
Re^2: resetting a foreach loop!
by ikegami (Patriarch) on Nov 17, 2017 at 19:16 UTC

    Your average specifically checks if no arguments are provided, but doesn't actually handle that situation. Fixed:

    sub average { if (@_) { my $sum; for (@_) { $sum += $_; } return $sum/@_; } else { return undef; } }

    Same, but shorter:

    sub sum { my $sum; $sum += $_ for @_; $sum } sub avg { @_ ? sum(@_)/@_ : undef }

      ++Indeed. Technically, the no-explicit-return version of the function returns 0 for an empty argument list, so it implictly handles the empty case. (I infer that the OP did the if(@_) just to prevent divide-by-zero.) But I agree that explicit undef is a better return value than relying on a default 0.

        Technically, the no-explicit-return version of the function returns 0 for an empty argument list

        I am aware of that, but they are relying undefined behaviour to do so[1], and it's a poor value to return.

        I infer that the OP did the if(@_) just to prevent divide-by-zero.

        That would actually have been a far better outcome!


        1. "If no return is found and if the last statement is an expression, its value is returned. If the last statement is a loop control structure like a foreach or a while , the returned value is unspecified. The empty sub returns the empty list."
Re^2: resetting a foreach loop!
by lunette (Acolyte) on Nov 16, 2017 at 22:24 UTC
    that fixed everything, thank you so much!!
      Sorting the same array twice and assigning the results to two new arrays, potentially very long, is a bit wasteful when all you want is to find the smallest and largest value in the array. You could for instance do something like this:

       my($largest, $smallest) = (sort { $b <=> $a } @array)[0,-1];

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1203627]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-04-26 01:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found