perl 系统命令重定向到日志文件

标签 perl

我正在尝试将 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 程序员)强烈推荐使用 strictwarnings脚本中的编译指示。这将帮助您发现脚本中的任何错误或潜在问题。完成此操作后,必须使用 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/

相关文章:

perl - 使用或不使用 namespace::sweep 和/或 Modern::Perl

perl - Linux:如何安装 DBD::Pg 模块?

perl - IPC::Open3::open3() 不适用于 perl 5.14.2 和 perl 5.10.1?

perl - 使用 VBScript 或 Perl 发布 Twitter 状态更新的简单方法

perl - 我在 Postgresql 中的 utf-8 字符串发生了什么变化?

linux - 如何使用带有 Perl -e 参数的 cat 读取文件?

perl - 如何获取 Perl/Tk 文本小部件中的文本?

php - 如何使用 perl/php/grep/etc 从 csv 中提取日期范围?

Perl IO::Socket 计时问题

perl - perl 中的异常处理