我正在尝试将 perl 系统命令重定向到带有以下代码和时间的输出文件,但它不起作用?
$cmd="echo hi";
($second, $minute, $hour) = localtime();
$time="$hour:$minute:$second";
system("$time>new.txt");
system("$cmd 1>>new.txt 2>>&1");
最佳答案
如果你想写变量$time
到文本文件,open
一个可写的文件句柄并将其打印到您的文件中。
open(my $outfile, '>', 'new.txt');
print $outfile $time;
...
其次,您的输出重定向应为:
1>>new.txt 2>&1
这意味着“将 STDOUT (1) 附加到 new.txt,将 STDERR (2) 重定向到 STDOUT (1)”。有
>>
对第二部分没有意义。最后,我(以及所有其他 perl 程序员)强烈推荐使用
strict
和 warnings
脚本中的编译指示。这将帮助您发现脚本中的任何错误或潜在问题。完成此操作后,必须使用 my
声明所有变量。 ,这是一个无论如何都要养成的好习惯。所以毕竟,你的脚本应该是这样的:# recommended pragmas:
use strict;
use warnings;
# declare all new variables with "my"
my $cmd="echo hi";
my ($second, $minute, $hour) = localtime();
my $time="$hour:$minute:$second";
# open a writeable filehandle and print to the filehandle
open(my $outfile, '>', 'new.txt');
print $outfile $time,"\n"; # I've added a newline character here so that
# the time and the command's output are on different lines ;)
system("$cmd 1>>new.txt 2>&1");
关于perl 系统命令重定向到日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9922899/