guybrush has asked for the wisdom of the Perl Monks concerning the following question:
Hi, I'm trying to run a command on a unix box using system because I need the exit code. but I also need the stdout and stderr. so I try some STDOUT redirection unfortunatelly it works if I redirect to a file:
open(STDOUT, '>' ,"kk.txt" ) or die "Can't redirect stdout: $!";
But not when I do it to a variable:
open(STDOUT, '>' ,\$output ) or die "Can't redirect stdout: $!";
This is my Testing code:
#!/usr/bin/perl my $exitcode ; my $output=''; my $error=''; # take copies of the file descriptors open(OLDOUT, ">&STDOUT"); open(OLDERR, ">&STDERR"); #close current outs as per manual of open close(STDOUT) or die "Can't close STDOUT: $!"; close(STDERR) or die "Can't close STDERR: $!"; # redirect stdout and stderr open(STDOUT, '>' ,\$output ) or die "Can't redirect stdout: $!"; #open(STDOUT, '>' ,"kk.txt" ) or die "Can't redirect stdout: $!"; open(STDERR, '>' ,\$error ) or die "Can't redirect stderr: +$!"; printf "Before system\n"; # run the program system("echo I cant get this into a variable"); $exitcode=($? >>8); printf "After System\n"; # close the redirected filehandles close(STDOUT) or die "Can't close STDOUT: $!"; close(STDERR) or die "Can't close STDERR: $!"; # restore stdout and stderr open(STDOUT, ">&OLDOUT") or die "Can't restore stdout: $!"; open(STDERR, ">&OLDERR") or die "Can't restore stderr: $!"; # avoid leaks by closing the independent copies close(OLDOUT) or die "Can't close OLDOUT: $!"; close(OLDERR) or die "Can't close OLDERR: $!"; printf "Exitcode: %d\n" ,($exitcode); printf "still here\n"; print $output ; print $error ;
Please any help on why it does not work the redirection when is a variable?
Also if posible. how can I do this without system. remember I need exitcode stdout and stderr and I do not want to do any alter to the actual command to do unix redirections.
Many many thanks.
Guybrush.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: system stdout redirected ok to a file but not to a variable.
by salva (Canon) on May 28, 2015 at 21:18 UTC | |
|
Re: system stdout redirected ok to a file but not to a variable.
by graff (Chancellor) on May 28, 2015 at 23:03 UTC | |
|
Re: system stdout redirected ok to a file but not to a variable.
by Anonymous Monk on May 28, 2015 at 22:27 UTC | |
|
Re: system stdout redirected ok to a file but not to a variable.
by GotToBTru (Prior) on May 28, 2015 at 21:08 UTC | |
|
Re: system stdout redirected ok to a file but not to a variable.
by guybrush (Initiate) on May 29, 2015 at 07:31 UTC | |
by locked_user sundialsvc4 (Abbot) on May 29, 2015 at 13:34 UTC |