Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2017-06-28 23:02 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (652 votes). Check out past polls.