Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi.

I got a string which has different words split up by pipeline characters ("|"). The number of words is totally variable.

So, for example at a point my string has the following values "a|b|c|d|e".

How can I tell Perl to get each word split by the pipechars and push them into a list(array)? Remember that the number of words in the string (split by pipes) can be any. It's not a fixed one.

Thanks,
Ralph :)

Replies are listed 'Best First'.
Re: Splitting a String
by damian1301 (Curate) on May 18, 2001 at 05:00 UTC
    @array=split/\|/,$str;

    You have to backslash it because it is used in regular expressions as a logical or.

    NOTE:This could have been found out by using the tutorials, super search or just looking through the archives...

    Tiptoeing up to a Perl hacker.
    Dave AKA damian

Re: Splitting a String
by TheoPetersen (Priest) on May 18, 2001 at 05:03 UTC
    The answer appears so many times in your post that I wonder if you are testing the community to see how nice we can be :)

    It's perlfunc:split of course. Pass it a regular expression and your string and you'll get the array of choice back.

    @ary = split(/|/, $string);

    Go read the documentation though, split does other nice tricks too.

Re: Splitting a String
by rob_au (Abbot) on May 18, 2001 at 05:05 UTC
    The command that you are looking to use is split. The command allows you to split a string into an array based on an arbitrary pattern that you define. This command takes the format;

    @result = split (/PATTERN/, EXPR, LIMIT)

    If EXPR is omitted, this command splits the contents of the $_ string. If the PATTERN argument is also omitted, this command will split on whitespace (after skipping any leading whitespace). Anything matching pattern (in this case, you would want to use '|') is taken as the delimiter between fields.

    The LIMIT argument allows you to split EXPR into no more than LIMIT fields. This is very useful if you only need to extract a certain number of fields from EXPR.

    You can compare this command to the join statement.