2017年1月25日水曜日

Edit CSV with Perl - use foreach

the previous script was really agree. rewrite it to process multiple files in a sequence. the list of file name is stored in the array. loop to process each element. thus eliminating overwrapping parts in the script.

use strict;

use Text::CSV_XS;
my $csv = Text::CSV_XS->new ({ binary => 1 }); # open file w/ binary mode
# prepare array to store input file names;
my @inputfile = ("emp_in.csv","os_in.csv");
# "foreach" extracts filename, stores in $count and loop till the end of array
foreach my $count(@inputfile){
  print "input file = $count\n"; # this line is for debug
  open my $fh, "<", $count; # case for foreach
  while (my $columns = $csv->getline ($fh)) {
    # columns no 3 stores bug id(s) which might be concateated with ,
    $$columns[3] =~ s/ //g; # eliminate unnecessary space from column no.3
    $$columns[3] =~ s/,/;/g; # replace , by ;
    my $rm_id = ""; #initialize the parameter.
    # if columns includes # the line is header. it is defunct.
    if($$columns[0] =~ /#/){
      # do nothing here!
    }else{ # if not a header, do below
      $rm_id = $$columns[0];
    }
    if($$columns[3] =~ /[0-9]/){  # if $$columns[3]= TFS bug ID includes any bug
      # print $$columns[0]," ",$$columns[3],"\n";
      my @bug_num = split(/;/,$$columns[3]);
      foreach my $parts(@bug_num){
        print "$rm_id;$parts\n";
      }
    }
  }
  close $fh;
  # print "close fh\n";  # this is for debug
}
$csv->eof;

0 件のコメント: