in reply to Re: To Split or Not to Split
in thread To Split or Not to Split

“Use split when you know what to throw away and a regex when you know what to keep.”

Except that that doesn’t really work, considering that:

  1. Because split takes a regex as its own argument, you cannot oppose “split” with “regex”: wherever you have split, there too do you also have a regex. It’s like some sort of logic error.

  2. Sometimes split does not necessarily throw (all of) what it matches away.
    $str = "this here and that or those there and his or hers nor thee"; @words = split /\h*\b(and|nor|or)\b\h*/, $str;
  3. A regex doesn’t always return (all of) what it matches.
    $str = "fee=1 fie=2 foe=3 fum=4"; my %settings = $str =~ /\b(\w+)=(\S*)/g;
    and also, in a completely different way:
    % perl -pe 's//IoException/ if ?import java\.io\.\KFile?'

So I would be careful with passing along that particular phrase. It’s catchy, but it isn’t really all that correct. Perhaps it was originally said about some other language than Perl, since it doesn’t seem to make sense for Perl when looked at closely.

At most I might point out that m//g and split are often used in complementary senses, with one looking for the parts you’re interested in and the other for the parts you’re not. Even so, in many contexts I’d hasten to add that while they might kinda work that way in common cases, that’s much too simplistic a description for what you can — and quite often do — do with both of these constructs in Perl.

Let’s just say that the refrain presents a rather simplified version of reality. :)

Replies are listed 'Best First'.
Re^3: To Split or Not to Split
by Corion (Patriarch) on Apr 25, 2011 at 07:59 UTC

    Maybe "match" is a better term than "regex", but still, I also found that most of the time when I despaired trying to make split do my bidding, a match would easily collect the information I wanted (and knew how) to keep.