Radial Software

Home Tips Perl Using the split() function

Using the split() function

There appears to be a minor quirk in the Perl split() function.

This function is used to split a string of delimited values into an array of individual elements and is extremely useful when dealing with comma-separated files

- it is typically used as follows:

    @array = split(',', $string);

However, the other day I needed to split a string that was delimited with the 'pipe' character (the vertical bar '|') and was surprised to discover that the following doesn't work as expected:

    @array = split('|', $string);

This does return a result, but splits $string into an array of character, without regard for the pipe delimiter. The solution is straightforward; you need to 'escape' the pipe character by using a backslash and/or use a regular expression:

    @array = split('\|', $string);

or:

    @array = split(/\|/, $string);

I suspect it's because the official instantiation of split() expects a regular expression, rather than a character literal, but perhaps someone can confirm?



 

Add your comment

Your name:
Comment:

Opinions

Favorite Programming Language
 

Search


Online

We have 2 guests online

Services

We have significant experience in developing software products for business users in many different sectors - if your business needs an automated solution

Read more...

News

The UK Government has announced that it intends to increasingly adopt 'open-source' software, in preference to traditional 'propriety' software.

Read more...