繁体   English   中英

Perl 用于将 header 添加到文件的简单单行在输入文件为空时不起作用

[英]Perl simple one-liner used to add header to a file doesn't work when input file is empty

我们在代码中使用单行代码将 header 添加到文件中。 看起来像

perl -pi -e 'print "name, function, group\n" if $. == 1' CSV_FILE_NAME

一切都很好,除非 CSV_FILE_NAME 为空,然后没有 header 被添加到 CSV_FILE_NAME。 所以这个命令之后的 CSV_FILE_NAME 仍然是空的。

巴托什,

这个单行代码不适用于空文件,因为实际上它看起来是这样的:

perl -MO=Deparse -i -pe 'print "name, function, group\n" if $. == 1' test.txt
BEGIN { $^I = ""; }
LINE: while (defined($_ = readline ARGV)) {
    print "name, function, group\n" if $. == 1;
}
    continue {
    die "-p destination: $!\n" unless print $_;
}

readline()尝试从一个空文件中读取时,它会立即命中eof (文件结尾)并且while循环立即结束。 因此,无论尝试什么变通方法,例如将对system()的调用放入else{ }块:

perl -i -pe 'if ($.==1) { print "1, 2, 3\n" } else { system("echo 1, 2, 3 > test.txt") }' test.txt 

这个块将没有机会被执行:

BEGIN { $^I = ""; }
LINE: while (defined($_ = readline ARGV)) {
if ($. == 1) {
    print "1, 2, 3\n";
}
else {
     system 'echo 1, 2, 3 > test.txt';
     }
}
continue {
    die "-p destination: $!\n" unless print $_;
}

一种解决方案是用一些东西“填充”空文件,使它们不为空。 此脚本在每个空文件中输入一个新行:

use strict;
use warnings;

foreach my $file (@ARGV) # for each file on the command line: primer.pl file1 file2 file3...
{
  if (-z $file) # if the file has zero size
  {
    open my $fh, ">>", $file or die "$0: Cannot open  $file: $!";
    print   $fh "\n";
    close   $fh              or die "$0: Cannot close $file: $!";
  }
}

在您的空文件上运行此脚本后,您可以在它们上应用您的单线,它会按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM