in reply to Split operator in perl

Using a quantifier (+,*,?,{m,n}) on a capture rarely makes sense. If you didn't want to capture: /(?:a|b)+/ or /[ab]+/. If you wanted to capture the whole separator: /((?:a|b)+)/ or /([ab]+)/.

Then there's the fact that your separator is probably not really a separator since one a matching pattern is found at the start of the string. This will cause you to have a leading empty field.

What are you expecting for output?

Replies are listed 'Best First'.
Re^2: Split operator in perl
by binesh_28 (Initiate) on Dec 06, 2010 at 07:58 UTC

    I was pretty confused trying to understand the results from that operation. I wasn't trying to accomplish any other task. That was one of the examples quoted as part of perl docs, and as a beginner to perl, I was having a hard time trying to figure out the results. Thanks for your help.

      As a beginner to Perl, maybe you shouldn't worry about what weird results split will give if you give it weird inputs. I bet most Perl experts would have to guess at what 'ab'=~/(a|b)+/ returns (although they would likely guess correctly). More important would be to learn how to use split properly.

      • The regular expressions should identify the separator. In your case, it doesn't appear to be used to match a separator, so split is probably not the best tool for the job.

      • You'll rarely want to use captures in a split pattern. When you do, what the captures match is returned in split's result.

      • Using a quantifier on a capture doesn't make sense. If you want to group things in patterns, use (?:...) instead of (...). The latter is much slower since it remembers what the parens matched, and has side effects in split.