Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
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

Replies are listed 'Best First'.
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?
[GotToBTru]: you're mixing notation there I think
[GotToBTru]: $aohoaoh->[0] is a hash reference, so $aohoaoh->[0]->{ key1} would work
[1nickt]: If 1nickt is the some guy, that's not what he said.
[GotToBTru]: thepkd might not know about last hour of cb
[1nickt]: my $x = $aohoaoh->[0]->{' foo'}->[0]->{'bar' }; should work
[thepkd]: its not $aohoaoh->[0]. its $aohoaoh[0]->{'foo '}. Tried it. Its working. Thnaks
[thepkd]: Hey 1nickt sorry man. What
[GotToBTru]: a ref too far ;)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2016-12-06 13:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (105 votes). Check out past polls.