Quote from: obemathortai on Sun, 2011-05-15 : 21:32
Please provide a perl script that will sort a CSV file by first column, then second, and then insert into a mysql database.
Sample data:
f1,f2,f3
I,am,writing a script
I,be,using perl for it
That,should,sort first by column one
That,will,sort second by column two
Finally,will,insert into the database
All,data,that it finds
Script:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use Tie::Handle::CSV;
my $CSV_FILE = $ARGV[0] || die "$0 csv-file";
my $DSN = q{DBI:mysql:database=test;host=localhost};
my $DBH = DBI->connect($DSN, 'test', 'test', { 'RaiseError' => 1 });
my $FH = Tie::Handle::CSV->new($CSV_FILE, header => 1);
my $HASH = {};
while (my $csv = <$FH>) {
if (! defined($HASH->{$csv->{'f1'}}->{$csv->{'f2'}})) {
$HASH->{$csv->{'f1'}}->{$csv->{'f2'}} = [];
}
push(@{ $HASH->{$csv->{'f1'}}->{$csv->{'f2'}} }, $csv);
}
my $STH = $DBH->prepare( q{ INSERT INTO t1 VALUES(?, ?, ?) } )
|| die "Prepare failed: $!";
for my $f1_key (sort keys %{$HASH}) {
for my $f2_key (sort keys %{$HASH->{$f1_key}}) {
my @array = @{ $HASH->{$f1_key}->{$f2_key} };
for my $line (@array) {
$STH->execute($f1_key, $f2_key, $line);
}
}
}
END {
close($FH) if defined $FH;
$DBH->disconnect if defined $DBH;
}
MySQL output:
+---------+--------+-----------------------------------------+
| f1 | f2 | f3 |
+---------+--------+-----------------------------------------+
| All | data | All,data,"that it finds" |
| Finally | will | Finally,will,"insert into the database" |
| I | am | I,am,"writing a script" |
| I | be | I,be,"using perl for it" |
| That | should | That,should,"sort first by column one" |
| That | will | That,will,"sort second by column two" |
+---------+--------+-----------------------------------------+