使用 Printf (Perl) 将输出打印到文件

Print output to a file using Printf (Perl )

我在下面有现有的脚本和脚本的一部分 post。我想将结果打印到文件中。结果打印在 Linux 屏幕会话中 我的问题是如何将 def 打印到文件而不是在屏幕上显示

my $def=printf '/opt/bin/run server=%s os="%s" version=%s application=%s',
    $server, $os, $version, $application;       
print $def."\n" ;

以下是如何将字符串写入文件的示例:

use strict;
use warnings;

my $str = 'hello world';
my $fn = 'hello.txt';
open ( my $fh, '>', $fn ) or die "Could not open file '$fn': $!";
print $fh $str;
close $fh;

如果您查看 the documentation for print(),您会发现它采用以下形式:

printf FILEHANDLE FORMAT, LIST
printf FILEHANDLE
printf FORMAT, LIST
print

您目前正在使用列表中的第三种形式。如果你想printf()的输出到一个文件,你可以切换到第一种形式。

# open a filehandle for your file
open my $fh, '>', $your_file_name or die "$your_file_name: $!";

printf $fh '/opt/bin/run server=%s os="%s" version=%s application=%s',
       $server, $os, $version, $application;

请注意(如 print())文件句柄和其他参数之间没有逗号。