Yokupoku Maioku
Yokupoku Maioku

Reputation: 503

escape special character in perl when splitting a string

i have a file in this format

string: string1
string: string2
string: string3

i want to split the lines by space and :,so initially i wrote this:

my @array = split(/[:\s]/,$lineOfFile);

the result wasn't as expected, because inside @array the split inserts also white space , so after some researches i understood that i have to escape the \s so i wrote

my @array = split(/[:\\s]/,$lineOfFile);

why i have to escape \s, the character : isn't a special character or not?

can someone explain me that?

thanks in advance.

Upvotes: 0

Views: 3495

Answers (3)

Borodin
Borodin

Reputation: 126762

You don't have to double up the backslash. Have you tried it?

split /[:\\s]/, $line

will split on a colon : or a backslash \ or a small S s, giving

("", "tring", " ", "tring1")

which isn't what you want at all. I suggest you split on a colon followed by zero or more spaces

my @fields = split /:\s*/, $line

which gives this result

("string", "string1")

which I think is what you want.

Upvotes: 2

hwnd
hwnd

Reputation: 70750

You do not need to double escape \s and the colon is not a character of special meaning. But in your case, it makes sense to avoid using a character class altogether and split on a colon followed by whitespace "one or more" times.

my @array = split(/:\s+/, $lineOfFile);

Upvotes: 2

Nemesis
Nemesis

Reputation: 2334

The problem is, that /[:\s]/ only searches for a single character. Thus, when applying this regex, you get something like

print $array[0], ' - ', $array[1], ' - ', $array[2];

string -  - string1

because it splits between : and the whitespace before string1. The string string: string1 is therefore splitted into three parts, string, the empty place between : and the whitespace and string1. However, allowing more characters

my @array = split(/[:\s]+/,$lineOfFile);

works well, since :+whitespace is used for splitting.

print $array[0], ' - ', $array[1];

string - string1

Upvotes: 1

Related Questions