Connecting Tech Pros Worldwide Forums | Help | Site Map

How can I CORRECTLY pass strings as arguments from command line?

Newbie
 
Join Date: Jul 2008
Posts: 1
#1: Jul 16 '08
Without going into details; I have the need to pass a string containing double backslashes \\ from the DOS command line and convert these to single backslashes in the code.

The problem is if I do this from within perl code directly it is no problem but when I attempt to pass a string from the command line, it seems to lose something in the translation and when I try to do the replace it does not work. So the question is HOW to pass the string from the command line so it works. Here is the sample code that works without passing from the command line:

perl source code = test_string_replace21.pl:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -w
  2. use strict;
  3. # replacing double back slash...
  4. my $string1 = "-----\\---------";
  5. $string1 =~ s/"\\"/"\"/g;
  6. print "The resulting value is : $string1 \n";

This of course works:
Expand|Select|Wrap|Line Numbers
  1. C:\>
  2. C:\>test_string_replace21.pl
  3. The resulting value is : -----\---------
As you can see, the double back slash is changed to a single one as expected.



But now use the following code which should do the same thing as above but takes the string as argument from the command line:

perl source code = test_string_replace2.pl:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl -w
  2. use strict;
  3. my $string1 = $ARGV[0];
  4. $string1 =~ s/"\\"/"\"/g;
  5. print "The resulting value is : $string1 \n";
  6.  
I run it from DOS command line:

Expand|Select|Wrap|Line Numbers
  1. C:\>test_string_replace2.pl "-----\\-----"
  2. The resulting value is : -----\\-----
As you can see, the double back slash is still there!!!!! Why????? And how do I get around it?

Thanks to anyone who can help.

numberwhun's Avatar
Site Moderator
 
Join Date: May 2007
Location: New Hampshire
Posts: 2,572
#2: Jul 16 '08

re: How can I CORRECTLY pass strings as arguments from command line?


Instead of enclosing the back slashes in double quotes, as you did in your first example, do it like so:

Expand|Select|Wrap|Line Numbers
  1. $string1 =~ s/\\\\/\\/g;
  2.  
the extra back slashes escape the meaning of the back-slash in the regular expression, which..... is to escape a character's meaning inside of a regex, thus, making the following back-slash, just a back-slash, without any special meaning.

Regards,

Jeff
Reply