简体   繁体   English

如何使用perl在新的变量名称中存储打印语句输出?

[英]How to store the print statement output in the new variable name using perl?

Is it possible to store the print statement into variable name using perl ? 是否可以使用perl将print语句存储为变量名?

Here is my print statement, 这是我的印刷声明,

print "$fixed\n";

I want to store the this print statement output in new variable. 我想将此打印语句输出存储在新变量中。 Is it possible to do? 有可能吗?

Just assign to a variable instead of print it: 只是分配给一个变量,而不是打印它:

my $var = "$fixed\n";

For more complex scenarios, use sprintf , example: 对于更复杂的场景,请使用sprintf ,例如:

my $var = sprintf("%02d - %s - %f", 1, $fixed, 3.1415);

The answer you have already seen an accepted does things in a slightly different order than you asked for. 您已经看到的答案的执行顺序与您要求的顺序稍有不同。 You asked: 您询问:

How to store the print statement output in the new variable name using perl? 如何使用perl在新的变量名称中存储打印语句输出?

The answer you have stores some data in a variable and then prints the contents of the variable. 您得到的答案将一些数据存储在变量中,然后打印该变量的内容。 That has the same effect, but it's not, strictly speaking, what you asked for. 具有相同的效果,但严格来说,这并不是您要的。

But it's possible to do anything in Perl. 但是可以在Perl中做任何事情。 Including configuring a scalar variable to store any data that is printed. 包括配置标量变量以存储所有打印的数据。

#!/usr/bin/perl

use strict;
use warnings;

my $output;

# Call open(), giving it a reference to a scalar, instead of
# a filename.
open my $fh, '>', \$output or die $!;

# Now anything printed to that filehandle, is appended to
# your scalar variable.
print $fh "this is\na test\n";

# ... which you can print to STDOUT
print $output;

It's possible to take this a step further, by using select() to make your scalar filehandle, the default output filehandle. 通过使用select()将标量文件句柄设为默认输出文件句柄,可以使此步骤更进一步。

select $fh;

print "Something";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM