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

Re: Finding average from numbers appearing in a file

by trizen (Hermit)
on Aug 05, 2012 at 08:44 UTC ( #985507=note: print w/replies, xml ) Need Help??

in reply to Finding average from numbers appearing in a file

use strict; use warnings; use Locale::Country; my @names = all_country_names(); # Better use Regexp::Trie my $countries_re = do { local $" = q{|}; qr/@{[map quotemeta, @names]}/i; }; my %hash; while (<>) { #if (/^.*?-([A-Z][A-Za-z\s\-]+[a-z])\s+(\d+)\s+hops?\b/is) { if (/^.*?-($countries_re)\s+(\d+)\s+hops?\b/is) { my ($country, $hops) = ($1, $2); $hash{$country} = { sum => ($hash{$country}{sum} || 0) + $hops, num => ++$hash{$country}{num} }; } } foreach my $key (sort keys %hash) { printf "$key avg: %.3f\n", $hash{$key}{sum} / $hash{$key}{num}; } __END__ Australia avg: 30.000 China avg: 22.667 Czech Republic avg: 19.500 France avg: 30.000 Germany avg: 8.500 Japan avg: 18.000 Netherlands avg: 9.500 United Kingdom avg: 8.000 United States avg: 19.667

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985507]
WinnieB bows, falls over, and tries to stand up again
[marto]: at least gravity is still working

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2017-03-30 06:49 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (353 votes). Check out past polls.