Bartosz,
This one-liner won't work on empty files because actually it looks this way:
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 $_;
}
When readline()
tries to read from an empty file, it immediately hits eof
(end of file) and the while
loop ends right away. So, whatever workarounds one may try, for example placing a call to system()
into the else{ }
block:
perl -i -pe 'if ($.==1) { print "1, 2, 3\n" } else { system("echo 1, 2, 3 > test.txt") }' test.txt
this block won't have the chance to be executed:
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 $_;
}
One solution is "to prime" empty files with something, making them non-empty. This script enters a new line into every empty file:
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: $!";
}
}
After you have run this script on your empty files, you can apply on them your one-liner and it will work as expected.