課題への挑戦
コード
#!/usr/local/bin/perl -w use strict; use warnings; use Data::Dumper; use constant OUTPUT_FILE => "union.csv"; my $path1 = $ARGV[0]; my $path2 = $ARGV[1]; eval { die "no argument." unless defined ( $path1 && $path2 ); die "no file argv1." unless ( -f $path1 ); die "no file argv2." unless ( -f $path2 ); my ( @master, @code ); &load_file( $path1, \@master ); &load_file( $path2, \@code ); &join_files( \@master, &get_code(\@code) ); }; if ( my $err = $@ ) { print "Exception: $err\n\n"; } sub load_file { my $file = shift; my $array_ref = shift; open ( READ, "<$file") or die "cannot open $file."; foreach ( <READ> ) { chomp; my @tmp = split(",",$_); push(@$array_ref, \@tmp); } close READ or die "cannot close $file."; } sub get_code { my $code_ref = shift; my $code; foreach (@$code_ref) { $code->{@$_[0]} = join(",", @$_); } return $code; } sub join_files { my $master_ref = shift; my $code = shift; open ( WR, "> " . OUTPUT_FILE ) or die "cannot open write file."; foreach ( @$master_ref ) { print WR join(",", @$_) . "," . $code->{$$_[0]} ,"\n"; } close WR or die "cannot close write file."; }
実行結果
$ perl -w csvConv.pl master.csv code.csv $ cat union.csv 123,aaa,bbb,123,test2,test_test,test5 456,iii,jjj,456,test4,test_test,test3 789,kkk,mmm,789,test6,test_test,test1 123,ccc,ddd,123,test2,test_test,test5 123,eee,fff,123,test2,test_test,test5 111,ggg,hhh,111,test1,test_test,test6
あれ、Perl ってこんな書き方したっけ?!とか思いながら書いている自分が嫌いになりましたorz
ぐだぐだ書き上げてから、2ファイルの中身を持ち回っている設計にゲンナリ。
ダメだ…コードリーディングもせねば…