用于向文件添加头的Perl简单一行程序不';输入文件为空时无法工作
我们在代码中有一个用于向文件添加头的行程序。看起来像用于向文件添加头的Perl简单一行程序不';输入文件为空时无法工作,perl,Perl,我们在代码中有一个用于向文件添加头的行程序。看起来像 perl-pi-e“print”名称、函数、组\n“if$。=”1'CSV文件名 一切正常,除非CSV_文件名为空,然后CSV_文件名中没有添加头。 所以这个命令后面的CSV文件名仍然是空的。Bartosz 这一行程序对空文件不起作用,因为实际上它看起来是这样的: perl -MO=Deparse -i -pe 'print "name, function, group\n" if $. == 1' test.txt BE
perl-pi-e“print”名称、函数、组\n“if$。=”1'CSV文件名
一切正常,除非CSV_文件名为空,然后CSV_文件名中没有添加头。
所以这个命令后面的CSV文件名仍然是空的。Bartosz
这一行程序对空文件不起作用,因为实际上它看起来是这样的:
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
(文件结束),而循环会立即结束。因此,无论您尝试何种解决方法,例如将对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: $!";
}
}
在空文件上运行此脚本后,可以对其应用一行程序,它将按预期工作。如果文件为空,则没有第1行。所以页眉没有被写入。您可以考虑一些解决方案。