perl打印到stdout而不是打印到文件

时间:2014-06-02 17:01:25

标签: perl file-io stdout heredoc

所以我在这个人的头上碰到了我的头,说实话,我觉得我错过了一些简单的东西。我也认为我的问题是herdoc出了问题,或者我使用STDIN的方式出了什么问题。

Anywho,当我在命令行上运行以下脚本(是以root身份运行),而不是打印到文件时,它只是打印到STDOUT,这让我感到困惑。

sub do_stuff {
    my $resp = <STDIN>;

    my $service_file = <<END_FILE;
[Unit]
Description = tc hack for perist across reboot
After = syslog.target network.target nss-lookup.target

[Service]
Type = simple
ExecStart = /etc/tc/tcconfig.sh
ExecReload = /bin/kill -HUP \${MAINPID}
ExecStop = /bin/kill -INT \${MAINPID}
TimeoutSec = 30
Restart = on-failure
LimitNOFILE = 32768

[Install]
WantedBy = multi-user.target

END_FILE
    my $service_path = '/etc/systemd/system/multi-user.target.wants/tc.service';

    open(my $sfile, ">", $service_path)
      || die "can't open file for write ($service_path) $!";
    print $service_file;
    close $sfile;

}

这个命令行的输出是:

[Unit]
Description = tc hack for perist across reboot
After = syslog.target network.target nss-lookup.target

[Service]
Type = simple
ExecStart = /etc/tc/tcconfig.sh
ExecReload = /bin/kill -HUP ${MAINPID}
ExecStop = /bin/kill -INT ${MAINPID}
TimeoutSec = 30
Restart = on-failure
LimitNOFILE = 32768

[Install]
WantedBy = multi-user.target

输出正在打印到命令行而不是文件。不知道为什么。任何帮助非常感谢!

干杯

2 个答案:

答案 0 :(得分:4)

您需要指定正确的FH:

print $sfile $service_file;

答案 1 :(得分:3)

您打开文件句柄但不打印到它:

open(my $sfile, ">", $service_path)
      || die "can't open file for write ($service_path) $!";
print $service_file;
close $sfile;

应该是:

open(my $sfile, ">", $service_path)
      || die "can't open file for write ($service_path) $!";
print $sfile $service_file;
close $sfile;