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...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: I want to run a script from another script, use the same version of perl, and reroute IO to a terminal-like textbox
by ric00015 (Beadle) on Oct 01, 2013 at 16:41 UTC | |
by Perlbotics (Archbishop) on Oct 01, 2013 at 17:01 UTC | |
by ric00015 (Beadle) on Oct 01, 2013 at 17:30 UTC | |
|
Re^2: I want to run a script from another script, use the same version of perl, and reroute IO to a terminal-like textbox
by ric00015 (Beadle) on Oct 01, 2013 at 17:00 UTC |