“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. :)


In reply to Re^2: To Split or Not to Split by tchrist
in thread To Split or Not to Split by burningredmoon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.