tags:

views:

2026

answers:

5

I have the following string:

$_='364*84252';

The question is: how to replace * in the string with something else? I've tried s/\*/$i/, but there is an error: Quantifier follows nothing in regex. On the other hand s/'*'/$i/ doesn't cause any errors, but it also doesn't seem to have any effect at all.

+3  A: 

I'm having no such error. Can you post a complete code sniplet?

Leon Timmermans
+7  A: 

Something else is weird here...

~> cat test.pl
$a = "234*343";
$i = "FOO";

$a =~ s/\*/$i/;
print $a;

~> perl test.pl
234FOO343

Found something:

~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/$i/;
print $a;

~> perl test.pl
Quantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.

Solution, escape the special characters from the variable using \Q and \E, for example (TIMTOWTDI)

~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/\Q$i\E/;
print $a;

~> perl test.pl
234*343
Vinko Vrsalovic
you could also use quotemeta http://perldoc.perl.org/functions/quotemeta.html
Brad Gilbert
+2  A: 
$ perl -le '$_="364*84252";s/\*/xx/;print'
364xx84252

Definitely works. Perhaps you're using double-quotes in a oneline instead of single quotes? I'm not sure - I can't reproduce your results at all. You'll need to give a bit more background to your problem, preferably with code we can run to reproduce your results.

Tanktalus
A: 

The error must be coming from $i. s/*/foo/ works fine.

+1  A: 

It must be a psh issue then. Running script with perl xx.pl does not throw any errors. Thanks for help ;)

Strings do their own escaping of backslashes. In this case you should probably double the backslashes to s/\\*/$i/

Leon Timmermans