Hi,
Using the text file given in the above question or request, if I may give you a head up.
So is it possible that i can find the average
Yes, it is Possible!
Say, you want to find the average for country china only , you might do something like so:
use warnings;
use strict;
my $total_number_of_hops = 0;
my $number_of_matches = 0;
while (<>) {
chomp;
if (/.+?-(china\s+?[0-9]+?\s+?hops?)/is) {
++$number_of_matches;
my ( $country, $number_of_hops, $hop ) = split /\s+/, $1, 3;
$total_number_of_hops += $number_of_hops;
}
}
printf "Average Number of Hops for China is %.2f",
$total_number_of_hops / $number_of_matches;
However, it becomes a whole new ball game, if you are considering, doing the same for all the countries in the file. But that also is not difficult, as it may look.
This is what you can do. Modifying the previous code a bit.
- change the regex in the if() to get all countries, including those that has space within their names,
- use data structure that get all the hops for each of the countries individually, then
- use either a for or a while loop or 'whichever', to get the countries and the average
- It's that simple ;-)
Here is the head up
use warnings;
use strict;
use Data::Dumper;
my $country_hop_ref = {};
while (<>) {
chomp;
if (/.+?-(([a-z\s+]+?)\s+?([0-9]+?)\s+?hops?)/is) {
push @{ $country_hop_ref->{$2} }, $3;
}
}
print Dumper $country_hop_ref;
That is the head up, you need to find the average, yourself!!!
Please check the following:
perldoc perldsc,
perldoc perllol,
perldoc perlref
UPDATE: run all the scripts in this post, using the text file given by the OP as arugment on the CLI.
Hope this helps.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.