handling perl string containing '@' and '$' with system function
If I had a perl string $newpw containing '@' and '$', (e.g. "5a@Wf7$X") how to pass it to the system function properly?
This does not work: system("/usr/local/bin/acthw -pw \"$newpw\""); |
Escape like this
var1="5a\@Wf7\$X"; system("echo $var1"); |
Quote:
Is there a solution which allow an arbitrary string inputed by a user? |
This works for me:
$var1 = 'asd@fgh$hjk'; print "$var1\n"; system("echo \'$var1\' "); output: asd@fgh$hjk asd@fgh$hjk you need to enforce single quotes to prevent un-needed interpolation. |
"Interpolation and escaping" can become the sort of issues that cause a seasoned programmer to look at you with an expression that vaguely resembles table-tennis, because in her (or his) own mind that's rather-exactly what's going on at the time.
If you have a literal string with "magical" characters in it, such as 5a@Wf7$X, then your Perl program needs to change that string into a character sequence that the shell program, upon receiving it, will change back into the original! (Take a moment to let the "ping-pong look" come and go...) ;) So what you need to do is to take a string that looks like this... 5a@Wf7$X ... and make it look like this... 5a\@Wf7\$X ... so that the shell-program you wish to run can change it back to the original ... 5a@Wf7$X (Actually, the shell itself performs this service...) So, what you need to do is to "escape" the string that you've been given so that the shell can then "un-escape" it back into the original string. Something like this extemporaneously-written bit of chicken-scratching might do it: $foo =~ s/[@$\]/\\\1/g; (ooh, ick!) might do it... Let me try to explain...
If you are extremely lucky, you will happily find that this regular-expression transforms your string consistently into a string that will eventually be transformed back to the original string. Fun stuff, huh? |
Yeah I started by trying something like that, but coudln't get the esc/unesc seq to perform correctly for the $ under use strict & -w, so went for single quotes eventually.
I'm sure these guys here (www.perlmonks.org) could come up with a version that does work. If you do go there, please post the answer, as I'd be glad to see it. |
Then there's the good old 'quotemeta' function:
Code:
#! /usr/bin/perl -w Code:
LQpowah.pl |
For me, it wasn't so much the perl print, that was fine, it was passing it out to system and still getting a 'clean/complete' string for the receiving prog.
|
All times are GMT -5. The time now is 02:45 AM. |