如何将POD部分变为变量:
pod2usage(-verbose => 99, -sections => "DESCRIPTION"); # Goes on STDOUT
=head1 DESCRIPTION
A description
=cut
我只想将DESCRIPTION
分配给变量,而不是在STDOUT
上显示。
我目前正在调查这种方式。它很复杂而且不起作用:
sub pod2scalar {
use File::Temp 'tempfile';
my ($fh, $filename) = tempfile(UNLINK => 1);
open OLDOUT, '>&STDOUT';
{
local *STDOUT;
open STDOUT, ">", $filename or warn "Can't open $filename: $!";
#pod2usage(@_); # Doesn't work... I don't know why...
print STDOUT "This is captured in \$str";
close STDOUT;
}
open STDOUT, '>&OLDOUT' or die "Can't restore stdout: $!";
close OLDOUT or die "Can't close OLDOUT: $!";
open $fh, "<", $filename or warn "Can't open $filename: $!";
my $str = do { local $/, <$fh> };
close $fh;
$str;
}
答案 0 :(得分:4)
您可以通过将引用传递给open
来代替文件名来打开输出的标量变量
然后,您可以提供文件句柄作为-output
的{{1}}选项的值,以便将数据发送到您的标量变量
您还需要设置pod2usage
-exitval
,以便您有机会使用已捕获的内容
看起来像这样
'NOEXIT'
答案 1 :(得分:2)
有一个优秀的perl库Capture::Tiny可以简化保存stdout / stderr。
默认pod2usage
退出程序,因此您必须指定-exitval => "noexit"
。
以下是一个完整的工作示例:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Pod::Usage;
use Capture::Tiny ':all';
=head1 DESCRIPTION
A description
=cut
my $stdout = capture_merged {
pod2usage(-verbose => 99, -sections => "DESCRIPTION", -exitval => "noexit");
};
say "## Captured";
say $stdout;
__END__
This will output:
## Captured
Description:
A description