I second what jethro said. Maybe use a Modulino (Example from 'Mastering Perl' - see link at end of article) ?
But since you asked... (because it is possible, not recommended):
use strict;
use warnings;
our $exchange = "before (set by caller)";
my $other_file = "this_other_thing.pl";
my ($out, $err) = redir_file( $other_file );
#-- proof of re-direction and import/export
print "Caller: GOT from STDOUT ($other_file): ",
join("\n\tOUT> ", "", split( /\n/, $out) ), "\n";
print "Caller: GOT from STDERR ($other_file): ",
join("\n\tERR> ", "", split( /\n/, $err) ), "\n";
print "Caller: Exchange : $exchange\n";
sub redir_file {
my $do_filename = shift;
#-- we DUP the current STREAMS and then we close the original stream
+s...
open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!";
open(my $olderr, ">&STDERR") or die "Can't dup STDERR: $!";
close STDOUT;
close STDERR;
#-- now, we re-open the streams with redirection into strings...
my $redir_stdout;
my $redir_stderr;
open( STDOUT, '>', \$redir_stdout ) or die "Cannot redirect STDOUT t
+o string: $!";
open( STDERR, '>', \$redir_stderr ) or die "Cannot redirect STDERR t
+o string: $!";
#-- this is like "do"... and exactly as insecure...
my $do_file_content = qx{cat $do_filename}; # e.g. use Slurp...
my $read = eval $do_file_content; # =8-O
#... now $exchange might have been updated
#-- now, we restore the previous streams...
open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!";
open(STDERR, ">&", $olderr) or die "Can't dup \$olderr: $!";
return ($redir_stdout, $redir_stderr);
}
Modified this_other_thing.pl (our...)
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
our $exchange;
print STDOUT "PRG: Hello World!\n";
print STDERR "PRG: Hello Err!\n";
print "PRG: Exchange: ", ( $exchange // '(nothing)'), "\n";
$exchange = "after (called program)";
Result:
Caller: GOT from STDOUT (this_other_thing.pl):
OUT> PRG: Hello World!
OUT> PRG: Exchange: before (set by caller)
Caller: GOT from STDERR (this_other_thing.pl):
ERR> PRG: Hello Err!
Caller: Exchange : after (called program)
Don't know if this works well for Windows and in threaded/forked environments...
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.