in reply to Re^2: copying records from one file to another with filter.
in thread copying records from one file to another with filter.
A few observations and comments:
You are reading in the entire file and saving it in an array of arrays, but then don't do anything with it. (Well, other than use the size of the array as a never terminating while() condition.) For that situation your loop probably should be
for (@input)rather than
while (@input)
You are searching for a YYYY-MM-DD pattern when your example data is in DD-MMM-YYYY format. You'll never find anything.
You should probably use the 3 argument form of open and lexical file handles. What you have isn't wrong particularly, but isn't considered best practices.
The way you are calculating 30 days is easy but fragile. You may be better off using one of the date calculation packages. It may be good enough here though, so take that with a grain of salt.
Here's a minor reworking of your posted script to be more efficient (and work, for certain values of "work").
#!/usr/bin/perl use strict; use warnings; my @months = ( qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/); # source file directory my $srcdir = '../source'; # source file name my $srcfile = $srcdir . '/vol.dat'; my $desdir = '../target'; my $desfile = $desdir . '/total_volume.csv'; # Open source file. open my $read, '<', $srcfile or die "Can't open the DAT file $!\n"; open my $write, '>', $desfile or die "Can't open the CSV file. $!\n"; print $write "Date,Total_Volume\n"; my ( $year, $month, $day ) = ( localtime( time() - 2592000 ) )[ 5, 4, +3 ]; $year += 1900; my $startdate = "$day-".$months[$month]."-$year"; while (<$read>) { if ( /^$startdate/ .. /\x4/ ) { chomp; my (@items) = split /,/; printf $write "%s,%d\n", $items[0], $items[1] + $items[2]; } } # probably not necessary but not a bad idea close $read or die "Couldn't close the DAT file: $!\n"; close $write or die "Couldn't close the CSV file: $!\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: copying records from one file to another with filter.
by avanta (Beadle) on Jan 13, 2010 at 01:58 UTC | |
by thundergnat (Deacon) on Jan 13, 2010 at 13:56 UTC |