Everyone else has said what the preferred solution is.

But nobody has explained why what you did was so slow.

Full details are in Mastering Regular Expressions. However the basic theory is that Perl does a recursive search for ways to try to match your pattern to the string. The match goes from left to right in the pattern and the string. So it first tries to match the first (.*) to the end of the string. Well then it fails to get the pipe. So it backs off and tries again. And it turns out that you are doing a scenario where there are a lot of wrong partial matches you have to try first.

If you change all of the (.*)s to (.*?)s then the RE would be faster. It would be safer still to change them to ([^\|]*)s. Split is even faster, but as you learn REs keep in mind the principle that ambiguity in the RE can result in unexpected slowdowns...

Cheers,
Ben

PS Style point. Split your data into data structures early and then access the data structures directly rather than using formatted strings. In the long run I have found that to be faster, safer, and simpler.


In reply to RE (tilly) 1: There has to be an easier way... by tilly
in thread There has to be an easier way... by bxjoh

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.