perlのテキスト処理でテンプレにしていること

エクセルのデータを固定長テキストファイルにします。
エクセルはテキストファイルにコピペすると、以下のようになるので、これをインプットにします。

正規表現以外でよく使う処理です。

コマンドライン引数を取り、引数の数をチェックする

#!/usr/bin/env perl
use strict;
use warnings;

my $num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: args.pl arg1 arg2\n";
exit;
}

ファイルを入力し、出力する

SJISのファイルを入力し、SJISで出力する場合

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Encode;

my $num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: args.pl arg1 arg2\n";
exit;
}

#infile
  my $filename = $ARGV[0];
    open(my $fh, '<:encoding(cp932)', $filename)
      or die "Could not open file '$filename' $!";

#outfile
  my $filename_out = $ARGV[1];
    open my $fho, '>:encoding(cp932)', $filename_out or die "$filename_out : $!";

テキスト処理

  • CRLFの改行コードを除去する(chompでなく)
  • タブ区切りのテキストをsplit関数で必要な項目を変数へ格納する
  • 可変長のテキストを固定長にする(スペース埋め)
  • システム日付をYYYYMMDD形式にする
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Encode;

my $num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: args.pl arg1 arg2\n";
exit;
}

#infile
  my $filename = $ARGV[0];
    open(my $fh, '<:encoding(cp932)', $filename)
      or die "Could not open file '$filename' $!";

#outfile
  my $filename_out = $ARGV[1];
    open my $fho, '>:encoding(cp932)', $filename_out or die "$filename_out : $!";

  while(<$fh>){

#remove_CRLF
    $_ =~ s/[\r\n]+\z//;

#split_tab_separated_line
    my ($id, undef, undef, $text, undef, undef, undef, $date) = split(/\t/, $_);

#SJISだったら何バイト?
    my $bytes = length encode('cp932', $text);

#space文字を入れる_固定長
    $text .= ' '  x (50 - $bytes);

#localtime_to_YYYYMMDD
    my($sec, $min, $hour, $day, $month, $year, $wday, $yday, $isdst) = localtime(time);
    $year += 1900;
    $month += 1;
    my $yyyymmdd = sprintf("%04d%02d%02d%02d%02d%02d", $year, $month, $day, $hour, $min, $sec);

#filler
    my $filler = ' ' x 256;

#output
    print $fho 'abcde' . $id .'あいうえお' . $text . 'aiueo'. $date . $yyyymmdd . $filler . "\r\n";

}