Skip to content

Instantly share code, notes, and snippets.

@poppen
Created July 31, 2011 13:07
Show Gist options
  • Save poppen/1116780 to your computer and use it in GitHub Desktop.
Save poppen/1116780 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
#
# Usage: this_script.pl original.csv > new.csv
#
use strict;
use warnings;
use utf8;
use Encode;
use Text::CSV;
my $tc = Text::CSV->new( { binary => 1, empty_is_undef => 1 } );
my $enc = find_encoding('cp932');
my $count = 0;
while (<>) {
# skip headers
if ( $count < 2 ) {
$count++;
next;
}
my $line = $enc->decode($_);
$tc->parse($line) or next;
my @fields = $tc->fields;
my @new_fields = (
_build_date( $fields[0] ), # Date
"電車代", # Name
_build_comment( \@fields ), # Comment
$fields[-3] # Debit
);
$tc->combine(@new_fields);
printf "%s\n", encode( 'utf8', $tc->string() );
}
sub _build_date {
my $date = shift;
my ( $yyyy, $mm, $dd ) = split /\//, $date;
return sprintf "%02d/%02d/%d", $mm, $dd, $yyyy;
}
sub _build_comment {
my $fields_ref = shift;
my @fields = @$fields_ref;
my ( $memo, $from, $to );
if ( defined( $fields[-1] ) ) {
$memo = $fields[-1];
}
if ( defined( $fields[2] ) && defined( $fields[3] ) ) {
$from = $fields[2] . "・" . $fields[3];
}
if ( defined( $fields[5] ) && defined( $fields[6] ) ) {
$to = $fields[5] . "・" . $fields[6];
}
if ( defined($from) && defined($to) ) {
return sprintf( "%s→%s", $from, $to );
}
elsif ( defined($from) && defined($memo) ) {
return sprintf( "%s:%s", $from, $memo );
}
elsif ( defined($memo) ) {
return $memo;
}
else {
return "None";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment