my($abc) = "fred<hello>3hello"; $abc =~ /^[^\d]{2,4}<([^>]+)>\d?\1$/;
That's quite a complex regex for a newbie. I'll explain by making a somewhat simpler version first:
/^[^\d]{2,4}<([^>]+)>\d?.*$/;
First it tries to match 2 to 4 characters that aren't digits (/[^\d]{2,4}/), attached to the front of the string (/^/).

Then it tries to match something between angle brackets; the thing should not contain a closing angle bracket itself (<([^>]+)>). Notice that there are (unescaped) parens in this part, so the regex engine will capture what it matches, and that'll be the word "hello"; it'll be put into the capture variable $1 because this is the first (actually, the only) set of parens in this regex.

Finally, it tries to match an optional digit (/\d?/); and then something more.

If you try to run it now, you'll see it captures the same thing, in this case.

Your original string is a bit more complex in that the final part must match "\1". This is something special, and it's not chr(1) (that would have been a second possible interpretation): it can only match the string that is in $1 earlier in this match ("hello", remember?). Note that /$1/ would not work: the regex engine would plug the current value of the variable $1 into the regex before it starts to try to match anything; that value would not change afterwards.

Also note that \1 will only match literal strings: this is not a regex. Using a variable in a regex would treat its contents as a regex. Using \1, it is as if quotemeta is applied to the contents of $1 before using it in the regex.

TL;DR:


In reply to Re: perl code question by bart
in thread perl code question by abcdef

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.