对多列文件中的每一列进行相同的编辑

Make the same edit for edit for each column in a multi-column file

我有多个包含不同列数的 CSV 文件,我需要将其重新格式化为固定格式的文本文件。

在这个阶段,我对需要编辑的列进行散列和取消散列,但这很乏味,而且我无法在不先更改程序的情况下添加新列。

有没有更简单的方法来读取、拆分和编辑所有列,而不管文件中的列数?

到目前为止,这是我的代码:

use strict;
use warnings;

my $input = 'FILENAME.csv';
my $output = 'FILENAME.txt';

open (INPUT, "<", "$input_file") or die "\n !! Cannot open $input_file: $!";
open (OUTPUT, ">>", "$output_file") or die "\n !! Cannot create $output_file: $!";

while ( <INPUT> ) {

    my $line = $_;
    $line =~ s/\s*$//g;

    my ( $a, $b, $c, $d, $e, $f, $g, $h, $i, $j ) = split('\,', $line);

    $a = sprintf '%10s', $a;
    $b = sprintf '%10s', $b;
    $c = sprintf '%10s', $c;
    $d = sprintf '%10s', $d;
    $e = sprintf '%10s', $e;
    $f = sprintf '%10s', $f;
    $g = sprintf '%10s', $g;
    $h = sprintf '%10s', $h;
    $i = sprintf '%10s', $i;
    $j = sprintf '%10s', $j;

    print OUTPUT "$a$b$c$d$e$f$g$h$i$j\n";

}

close INPUT;
close OUTPUT;

exit;

你的意思是这样的吗?

perl -aF/,/ -lne 'print map sprintf("%10s", $_), @F' FILENAME.csv > FILENAME.txt

只要您使用顺序变量,就应该使用数组。在这种情况下,由于您只使用一次数组,您甚至不需要做更多的事情,只是暂时持有它。

另外:使用词法文件句柄,这是更好的做法。

#!/usr/bin/env perl

use strict;
use warnings;

my $input_file  = 'FILENAME.csv';
my $output_file = 'FILENAME.txt';

my $format = '%10s';

open( my $input_fh, "<", $input_file ) or die "\n !! Cannot open $input_file: $!";
open( my $output_fh, ">>", $output_file ) or die "\n !! Cannot create $output_file: $!";

while (<$input_fh>) {
   print {$output_fh} join "", map { sprintf $format, $_ } split /,/;
}

close $input_fh;
close $output_fh;

exit;