Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Any improvement over the code possible??

by davido (Archbishop)
on Sep 21, 2012 at 18:08 UTC ( #994964=note: print w/ replies, xml ) Need Help??


in reply to Any improvement over the code possible??

I think I'd like to see a looser coupling between find_above_average and calculate_average. And I would move the prints outside of the subroutines, to make them more generic.

use v5.14; use warnings; use IO::Interactive qw( is_interactive ); use Scalar::Util qw( looks_like_number ); use List::Util qw( sum ); say "Enter a list of numbers to find above average numbers, one per li +ne:" if is_interactive; my @numbers = get_input(); say "No numbers entered. Exiting" and exit if ! @numbers; my $average = average( @numbers ); say "The average is $average"; say "The above-average numbers are:"; say "\t$_" for above_average( $average, @numbers ); sub average { return sum( @_ ) / @_; } sub above_average { my $average = shift; return grep { $_ > $average } @_; } sub get_input { chomp ( my @numlist = <STDIN> ); return grep { length $_ && looks_like_number($_) } @numlist; }

Update: s/&&/and/ to fix a precedence issue.


Dave


Comment on Re: Any improvement over the code possible??
Select or Download Code
Re^2: Any improvement over the code possible??
by tobyink (Abbot) on Sep 21, 2012 at 20:18 UTC
    my @numbers = (); say average(@numbers);
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (18)
As of 2015-07-01 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (6 votes), past polls