As you can see, you have an embarrassment of riches in the
replies. Some of them are purposefully terse and idiomatic because
it's something of a sport here when a SoPW doesn't give code
attempts. :P If you work with one of them and have follow-up questions, don't hesitate to ask, but post whatever code you tried to use.
You got an interesting but terminally slothful, half-right dose of
self-congratulation regarding the use of a database. This is not
necessary of course as several of the replies neatly addressed your
actual question, and need, and are trivial to adapt to many other
requirements if you can follow the code.
That said, some persons find SQL a more natural way of working with
data so it is an interesting and potentially useful thing to
do; there is no try®. Like so many things, it is semi-trivial in Perl if you know how.
Building on previous answers, here's how–
#!/usr/bin/env perl
use strict;
use warnings;
use Text::CSV_XS "csv";
use DBI;
my $csv_file = shift || die "Give a CSV file with sample data\n";
my $dbh = DBI->connect("dbi:SQLite::memory:"); # DB is ":memory:"
$dbh->do(<<"");
CREATE TABLE sampleData( sample, input, amount )
my $insert_h = $dbh->prepare(<<"");
INSERT INTO sampleData VALUES( ?, ?, ? )
csv( in => "test.csv",
on_in => sub {
my @values = @{ $_[1] };
$insert_h->execute(@values) if @values == 3;
});
my $tallies = $dbh->selectall_arrayref(<<"");
SELECT sample
,input
,SUM(amount)
FROM sampleData
GROUP BY sample, input
ORDER BY sample, input
csv( in => $tallies,
out => "outputfile.csv" );
You will need fairly recent versions of a couple of these for this
to run, Text::CSV_XS, DBD::SQLite.
An excellent overview of DBI recipes: DBI recipes. And a footnote for working with the data outside of Perl–
$dbh->sqlite_backup_to_file("newDBname.sqlite");
# ^^^ To go from ":memory:" to a file. Then you also have access to
# the DB via the command line with the sqlite executable.
# moo@cow[2574]~>sqlite3 "newDBname.sqlite"
# sqlite> select * from sampleData;
# 3211111|100|3.2
# 3211112|101|3.2
# ...et cetera...
Update: s/CVS/CSV/g for @all_the_nodes;#!!!
-
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.