splitting problem

J

Jan

Hi!
I have to split a string with a pattern which contains sometimes chars
like + \ (the code is needed in an interpreter, written in Perl, of my
own scripting language, so I never know the pattern exactly).

split(/$pattern/, $string);

It works well most of all time, but if the pattern is + the execution
of the program stops and perl prints an error message.

$pattern = '+';
split(/"$pattern"/, $string); #ok

$pattern = '#';
split(/"$pattern"/, $string); #doesn't work really, but no
error
#occurs

Can anyone tell me how to solve this problem?
 
G

Gunnar Hjalmarsson

Jan said:
I have to split a string with a pattern which contains sometimes chars
like + \ (the code is needed in an interpreter, written in Perl, of my
own scripting language, so I never know the pattern exactly).

split(/$pattern/, $string);

It works well most of all time, but if the pattern is + the execution
of the program stops and perl prints an error message.

$pattern = '+';
split(/"$pattern"/, $string); #ok

$pattern = '#';
split(/"$pattern"/, $string); #doesn't work really, but no error
#occurs

Can anyone tell me how to solve this problem?

I don't think any of those works, since you are actually trying to
split on the strings '"+"' and '"#"'.

You should escape special characters. Try:

split /\Q$pattern/, $string;

Also, stop asking questions in this newsgroup. It's defunct. Use
comp.lang.perl.misc instead.
 
N

nikolay

÷ ÐÉÓØÍÅ Fri, 31 Oct 2003 00:35:15 -0800, Jan ÎÁÐÉÓÁÌ:
Hi! Hi

split(/$pattern/, $string);

It works well most of all time, but if the pattern is + the execution
of the program stops and perl prints an error message.
This is most like '+' means repeat more than zero.
I recommend do something like that if you want pattern to be a string
(not regexp):
$pattern = "string";
$qpattern = quotemeta($pattern)
split(/$pattern/,$string);
 
J

Jan

Thank you, the examples work!
.... and excuse me about posting this thread in the wring newsgroup.
Jan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top