Suppose we have:
sub test {
print \"testing\\n\";
}
If there is a case where I want to have it print to stderr instead of stdout, i
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<<<