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

I have a question based on some examples in my very basic Perl book, which, I must admit, is "Perl for Dummies." (I know, I know, I'm going to buy the Llama as soon as my paycheck clears!) I'm quoting here directly from the book:
The split function does not normally return the delimiters in list items. You can use parentheses in your regular expression and split returns whatever is in the parentheses as items in the list....For example, when you run the following program, in which the | delimiter is enclosed in parentheses,
$TheRecord="Serling|Rod|Twilight Zone|"; @TheFields=split (/(\|)/, $TheRecord);
Perl returns
('Serling', '|', 'Rod', '|', 'Twilight Zone', '|')
You can supress your desire to have the delimiters returned by using the (?: extension to regular expressions. For example, given the following statements,
$TheRecord="Serling|Rod|Twilight Zone|"; @TheFields=split(/(?:\|)/, $TheRecord);
Perl returns
('Serling', 'Rod', 'Twilight Zone')
It seems to me that the second program is just a longer-winded way to return exactly the same results as you'd get if you used
@TheFields=split(/\|/, $TheRecord);
Is there a difference I'm not perceiving? And if so, why would the longer-winded version be used?

Replies are listed 'Best First'.
Re: using split delimiters
by krujos (Curate) on May 23, 2002 at 21:36 UTC
    You are correct. In this example the ?: is dumb. I can’t think of a case off hand where you would want to do that in a split, I don’t think one exists.... Other monks please correct me if I am wrong.
    thanks ---Mogaka
      You may want to do it with something like /begin(?:block)?/ - note the question mark quantifier, or maybe in case of a backreference. I know I've needed this once or twice; it's not terribly common however.

      Makeshifts last the longest.

        If you needed it for a backreference though you'd use normal ( ) braces instead of the (?: ) braces seen here which are specifically intended not to store their results.

Re: using split delimiters
by merlyn (Sage) on May 23, 2002 at 16:35 UTC
    Perl for Dummies is admitted even by the author to be rather non-idiomatic. Please get some other book soon.

    Originally posted as a Categorized Answer.

Re: using split delimiters
by amarceluk (Beadle) on May 23, 2002 at 16:52 UTC
    Yes, I'm getting the Llama ASAP. Probably tonight. Money's tight or I'd have bought it a week ago.

    Originally posted as a Categorized Answer.