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

I have come across a hurdle with some code I am currently writing and seek enlightenment from my fellow monks. I am wanting to set up a split statement to split a string based on either "," or "," - that is /,\s+/ and /\,/. I have attempted this with a split command thus:

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

The problem with this is that I seem to be getting an additional array field consisting of a single space - That is if $string is this@emailaddress.com, that@emailaddress.com, I have the following returned:

this@emailaddress.com that@emailaddress.com

This is most obviously an syntax error on my part, but an explanation of my fault to further my understanding would be appreciated much more than an immediate code solution. I can post the full segment of code where I am having this issue if need be, but have trimmed the post to contain only the most relevant information - /msg me if more information is needed.

Many Thanks

 

Ooohhh, Rob no beer function well without!

Replies are listed 'Best First'.
Re: split strangeness
by kschwab (Vicar) on Sep 10, 2001 at 18:13 UTC
    From "perldoc -f split":

    If the PATTERN contains parentheses, additional array elements are created from each matching substring in the delimiter.

    Perhaps split(/,\s{0,1}/,$string) would work for you ?,

    Update: I wasn't sure if you wanted to handle the comma and any amount of following spaces. split(/,\s*/,$string) if so.

Re: split strangeness
by Zaxo (Archbishop) on Sep 10, 2001 at 18:19 UTC
    The problem with this is that I seem to be getting an additional array field consisting of a single space

    That is the effect of parens in a split re. Try this: my @array = split(/,\s*/, $string);

    After Compline,
    Zaxo

Re: split strangeness
by suaveant (Parson) on Sep 10, 2001 at 18:19 UTC
    my @array = split(/,(\s+|)/, $string); # change to my @array = split(/,(?:\s+|)/, $string);
    to make the parens non-capturing

    Update Zaxo's is much better in practice... but if you ever do need grouping, (?: ) will not capture like ( ) will

                    - Ant
                    - Some of my best work - Fish Dinner