need_help has asked for the wisdom of the Perl Monks concerning the following question:

I am using backtick operators to execute a java command from my perl script.
If I give `java myprogram abc 2>&1` then my java program thinks that 2>&1 is another argument for it!!!!

Is there a way to redirect STDERR to both STDOUT and my logfile without
this problem happening, and still using backtick operators.

My perl script needs to run both on UNIX and windows2000 so I like to keep this simple. THanks !!

Replies are listed 'Best First'.
Re: Program arg interfering with redirecting STDERR to STDOUT
by BrowserUk (Patriarch) on Jul 23, 2004 at 23:07 UTC

    It's the shell in either environment that provides for the command line redirection syntax (2>&1). When you use backticks, the shell is bypassed unless you explicitly state it.

    Something along these lines might work.

    my $shell = $^O eq 'MSWin32' ? "$ENV{comspec} /c " : "$ENV{shell} /?"; ## Bad guess my @output = `$shell java yourprog 2>&1`;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon
Re: Program arg interfering with redirecting STDERR to STDOUT
by graff (Chancellor) on Jul 24, 2004 at 04:42 UTC
    You can (and SHOULD) install the MS-Windows port of the GNU Bash shell on the windows machine(s) -- believe me, you'll be glad you did, and not just because it gives you a way to make this script work the way you want.

    The command line you showed should work fine as-is on any unix box -- I'm pretty sure that whatever "default" shell is invoked by perl backticks under the various flavors of unix will do the right thing with that redirection syntax. (And if I'm wrong, it's probably because you're using something I haven't seen yet, which is possible. ;)

    As for running on windows, you could either make sure that "bash.exe" is installed in a common "PATH" directory, or else make sure that your script knows (and uses) the correct absolute path (e.g. "C:/gnu/bin/bash" or whatever); as BrowserUK noted above, just put bash at the beginning of the backtick command line.

Re: Program arg interfering with redirecting STDERR to STDOUT
by gmpassos (Priest) on Jul 24, 2004 at 22:34 UTC
    Try this:
    use IPC::Open3 ; open3(LOGREAD , LOGERROR, LOGWRITE, "java myprogram abc"); my @output = <LOGREAD> ; my @errors = <LOGERROR> ; close(LOGREAD , LOGERROR, LOGWRITE) ;

    Graciliano M. P.
    "Creativity is the expression of the liberty".