jtroy has asked for the wisdom of the Perl Monks concerning the following question:
I can't seem to figure out how to properly include double-quote characters inside arguments to an external program while capturing both the normal and error output from that program.
I have a text file called arguments.txt that contains the following lines (with an empty line at the end).
Test Hi (12" mix) test.txt
I have a program called test_args.pl that reads in the list of words from the arguments.txt file. It then calls an external program using each word as an argument and captures both the normal and error output. For this test, it simply prints the output.
### test_args.pl ### use strict; my @args; open (IN, "arguments.txt") or die; while (<IN>) { chomp; s|"|\\"|g; push @args, qq("$_"); } close (IN); my $arg_str = join(" ", @args); my $output = `print_args.pl $arg_str 2>&1`; print "Output:\n$output";
The external program, print_args.pl, prints to STDERR each argument it is passed on a separate line:
### print_args.pl ### use strict; for (my $i=0; $i<=$#ARGV; $i++) { print STDERR "Arg $i - $ARGV[$i]\n"; }
When I run test_args.pl, I get the following output:
Arg 0 - Test Arg 1 - Hi (12" mix) Arg 2 - test.txt Arg 3 - 2>&1 Output:
So Perl is interpreting the 2>&1 as an argument instead of redirecting stderr to stdout for the external program call, which is what I want. It fails to capture the output of print_args.pl since it's being written to sderr.
However, if I remove the " from the "Hi (12" mix)" argument, it interprets it correctly:
Output: Arg 0 - Test Arg 1 - Hi (12 mix) Arg 2 - test.txt
Even stranger to me is that, if there are an even number of double-quotes in all of the parameters, it is interpreted correctly:
Output: Arg 0 - Tes"t Arg 1 - Hi (12" mix) Arg 2 - test.txt
It's only when there are an odd number of double-quotes that Perl interprets 2&>1 as an argument. It's confusing because each argument seems to be interpreted correctly - the double-quotes just mess up the redirection.
I have tried this on both of my machines:
Win2k running Perl 5.8.4, ActiveState binary build 810 WinXP running Perl 5.6.1, ActiveState binary build 635
Can anyone shed some light on this for me? Am I doing something wrong? Could there be a bug in my versions of Perl? Or could it be an operating system issue?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: External Program Arguments Problem
by Stevie-O (Friar) on Dec 22, 2004 at 03:09 UTC | |
by ZlR (Chaplain) on Dec 22, 2004 at 13:55 UTC | |
by jtroy (Initiate) on Dec 22, 2004 at 19:15 UTC | |
by Anonymous Monk on Dec 23, 2004 at 02:31 UTC |