By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,178 Members | 971 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,178 IT Pros & Developers. It's quick & easy.

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

P: 1
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.
Jul 16 '08 #1
Share this Question
Share on Google+
1 Reply


numberwhun
Expert Mod 2.5K+
P: 3,503
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
Jul 16 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.