Re: Irregular Expression??
by Abigail-II (Bishop) on Feb 23, 2004 at 21:55 UTC
|
How do I determine that the variable contains a ' in the value.
There are many ways of doing so:
if ($a =~ /'/) {....}
if (index ($a, "'") >= 0) {....}
if (split ($a, "'", -1) >= 2) {....}
if ($a =~ y/'/'/) {....}
how would I change the value in the variable to
$a = "A\'\'Bcd"
That's not a clear question. First of all, "A\'\'Bcd" is the same string as "A''Bcd". Do you want backslashes in the resulting
value? Second, do you want to change the first quote?
The last quote? Quotes between "A" and "B"? All quotes?
Only quotes in the second position?
Abigail | [reply] [d/l] [select] |
|
|
| [reply] [d/l] |
|
|
I believe what you are actually looking for is
$a =~ s/\'/\\\'/g;
daN. | [reply] [d/l] |
|
|
Close, but I think this is actually what Red_Dragon is looking for:
$a =~ s/\'/\\\'\\\'/g;
Update: I was a bit too lazy on my copy job, you don't actually have to escape the '. So this will save you some keystrokes:
$a =~ s/'/\\'\\'/g;
-jbWare
| [reply] [d/l] [select] |
|
|
Re: Irregular Expression??
by Skeeve (Parson) on Feb 23, 2004 at 23:09 UTC
|
since no one really answerd the second part, here is my solution to it: $a=~ s/'/\\'\\'/g
if you always want to replace every ' by \'\' if there is at least one ' in $a you need not check that any ' is in $a. Just use the re to replace. If you want to do more to $a if there is a quote in $a, you might be able toturn it around: First replace, then do what you want to do. if ($a=~ s/'/\\'\\'/g) {
# there were quotes in $a
# do what you want to
}
| [reply] [d/l] [select] |
Re: Irregular Expression??
by ambrus (Abbot) on Feb 23, 2004 at 22:06 UTC
|
$n= $a=~ s/\46/\46\46/g;
if ($n)
{ print "Had $n quotes, doubled them\n"; }
else { print "No qoutes\n"; }
Update: it's 047, not 046.
| [reply] [d/l] |
|
|
$n= $a=~ s/\46/\\\46\\\46/g;
# ^^ ^^
:
:
| [reply] [d/l] |
Re: Irregular Expression??
by delirium (Chaplain) on Feb 24, 2004 at 13:23 UTC
|
$a =~ s/'/q!\'\'!/eg && print "Found a ' in \$a\n";
accomplishes both of your objectives. | [reply] [d/l] |
|
|
Why do you evaluate (s/.../e)?
$a =~ s/'/\\'\\'/g && print "Found a ' in \$a\n";
will do it as well - even better, since it doesn't need to evaluate.
| [reply] [d/l] |
|
|
That's fine if you're used to reading it. In cases where there are lots of backslashes and single-quotes, I think it's less ambiguous to quote with q!..!; I could have also done something like
$replace = q!\'\'!;
s/'/$replace/g;
...but I'm a sucker for a one-line solution. | [reply] [d/l] |
|
|
|
|
|
|
|
Re: Irregular Expression??
by Red_Dragon (Beadle) on Feb 27, 2004 at 13:04 UTC
|
Providers of Wisdom,
As a novice I am trying to pick up the best of Perl habits. Good information is like a drug and you all have contributed to my addiction. To all who responded, THANK YOU for having such patience with my ignorance.
R_D
| [reply] |