Is there a way to capture a subroutine's print output to a variable so I can send it to stderr instead?

走远了吗. 提交于 2019-12-01 03:43:25

Yes there is. print sends its output to the "selected" filehandle, which is usually STDOUT. But Perl provides the select function for you to change it.

select(STDERR);
&test;           # send output to STDERR
select(STDOUT);  # restore default output handle

The select function returns the previously selected filehandle, so you can capture it and restore it later.

my $orig_select = select(STDERR);
&test;
select($orig_select);

Perl's dynamic scoping via local() is not often used, but this strikes me as a good application for it:

test(); # to stdout
{
    open(local *STDOUT, ">&STDERR") or die "dup out to err: $!";
    test(); # to stderr, locally calling it "STDOUT"
}
test(); # to stdout again

The call to test() in the block above -- as well as to anything that test() itself might call -- will have STDOUT dynamically scoped to your duplicate of STDERR. When control leaves the block, even if by die()ing, STDOUT will be restored to whatever it was before the block

Generalized:

sub out2err(&) {
  my $user_block = shift;
  open(local *STDOUT, ">&STDERR") or die $!;
  $user_block->();
}

test();             # to stdout
out2err { test() }; # to stderr
test();             # to stdout

Meanwhile, you can also "capture a subroutine's print output to a variable."

Just pass a scalar ref to open:

#! /usr/bin/env perl
use common::sense;
use autodie;

sub tostring (&) {
  my $s;
  open local *STDOUT, '>', \$s;
  shift->();
  $s
}

sub fake {
  say 'lalala';
  say 'more stuff';
  say 1 + 1, ' = 2';
  say for @_;
}

for (tostring { fake(1, 2, 3) }) {
  s/\n/\\n/g;
  say "Captured as string: >>>$_<<<";
}

Output:

Captured as string: >>>lalala\nmore stuff\n2 = 2\n1\n2\n3\n<<<

This work for me

local *STDOUT;
open(STDOUT, ">", \$Result);
&test();
print $Result;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!