drose2211:
Sure thing: you can use a hash to hold an array of digit entries for each city you encounter, like this:
$ cat pm1207805.pl
#!usr/bin/perl
use strict;
use warnings;
use Text::CSV;
use List::Util qw(sum);
use Data::Dumper;
my $csv = Text::CSV->new();
my $FH = \*DATA;
my %accumulator;
# Gather the digits for the cities
while (my $row = $csv->getline($FH)) {
my $city = $row->[1];
my $digits = $row->[3];
push @{$accumulator{$city}}, $digits;
}
# What do we have to work with?
print "Data:\n", Dumper(\%accumulator), "\n\n";
# Dump our results
for my $city (sort keys %accumulator) {
my $num_rows = @{$accumulator{$city}};
print "$city: ", sum(@{$accumulator{$city}}) / $num_rows, "\n";
}
__DATA__
CA006139520,"WINDSOR RIVERSIDE, ON CA",2018-01-02,10
CA006139520,"WINDSOR RIVERSIDE, ON CA",2018-01-02,20
CA006139520,"WINDSOR RIVERSIDE, ON CA",2018-01-02,14
CA006138520,"NEW YORK",2018-01-02,11
CA006137520,"PHILADELPHIA, ON CA",2018-01-02,23
CA006137520,"PHILADELPHIA, ON CA",2018-01-02,25
CA006138520,"NEW YORK",2018-01-02,13
CA006138520,"NEW YORK",2018-01-02,19
When you run it, you should get:
$ perl pm1207805.pl
Data:
$VAR1 = {
'WINDSOR RIVERSIDE, ON CA' => [
'10',
'20',
'14'
],
'PHILADELPHIA, ON CA' => [
'23',
'25'
],
'NEW YORK' => [
'11',
'13',
'19'
]
};
NEW YORK: 14.3333333333333
PHILADELPHIA, ON CA: 24
WINDSOR RIVERSIDE, ON CA: 14.6666666666667
...roboticus
When your only tool is a hammer, all problems look like your thumb.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.