views:

45

answers:

4

I have a string containing lots of text with white-spaces like:

String str = "abc xyz def";

I am now passing this string as a command line argument to a perl file using C# as in:

Process p = new Process();
p.StartInfo.FileName = "c:\\perl\\bin\\perl.exe";
p.StartInfo.Arguments = "c:\\root\\run_cmd.pl " + str + " " + text_file;

In the run_cmd.pl file, I have the follwing:

open FILE, ">$ARGV[1]" or die "Failed opening file";
print FILE $ARGV[0];
close FILE;

On printing, I am able to copy only part of the string i.e. "abc" into text_file since Perl interprets it as a single argument.

My question is, is it possible for me to copy the entire string into the text file including the white spaces?

+2  A: 

If you want a white space separated argument treated as a single argument, with most programs, you need to surround it with " "

e.g run_cmd.pl "abc xyz def" filename

Try

p.StartInfo.Arguments = "c:\\root\\run_cmd.pl \"" + str + "\" " + text_file;

Side note:

I don't know about windows, but in Linux there's a number of arguments and maximum length of one argument limit so you might want to consider passing the string some other way, reading it from a tmp file for example.

miedwar
Hey miedwar, thanks a lot!! That helped.
venividivamos
+1  A: 

It's not perl -- it's your shell. You need to put quotes around the arguments:

p.StartInfo.Arguments = "c:\\root\\run_cmd.pl '" + str + "' " + text_file;

If text_file comes from user input, you'll likely want to quote that, too.

(You'll also need to escape any existing quotes in str or text_file; I'm not sure what the proper way to escape a quote in Windows is)

Joe
+2  A: 

It's a little bit of a hack, but

$ARGV[$#ARGV]

would be the last item in @ARGV, and

@ARGV[0 .. ($#ARGV - 1)]

would be everything before that.

coding_hero
Nice hack. It works.
venividivamos
Thanks! I'm still new here, so feel free to give me a point if you find it useful.
coding_hero
A: 

@meidwar said: "you might want to consider passing the string some other way, reading it from a tmp file for example"

I'll suggest you look into a piped-open. See http://search.cpan.org/~jhi/perl-5.8.0/pod/perlopentut.pod#Pipe_Opens and http://perldoc.perl.org/perlipc.html#Using-open()-for-IPC

These let you send as much data as your called code can handle and are not subject to limitations of the OS's command-line.

Greg