Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Possessive sub-pattern with non-greedy content + recursion: WHY does this work??

by ikegami (Patriarch)
on Aug 04, 2025 at 21:09 UTC ( [id://11165956]=note: print w/replies, xml ) Need Help??


in reply to Possessive sub-pattern with non-greedy content + recursion: WHY does this work??

Your question appears to be "why is the anchor needed?"

Honestly, instead of spending time analysing your code, I'd rather show how to write this cleanly. Especially since your code doesn't think 1221 is a palindrome.

First, let's define palindrome.

An empty string? No. Too weird.
A single character? No. Again, too weird.

So a palindrome looks like this:

  • xx
  • xyx
  • axxa
  • axyxa
  • baxxab
  • baxyxab
  • ...

Since the minimum length of a palindrome (as we defined it) is two, we see it's always going to be a pair of matching chars, with the following in between:

  • Nothing ("xx")
  • A single character ("xyx")
  • A palindrome ("a...a", "b...b", ...)

So we get

echo abABCDCBAdeXYZYXfg1221 | perl -Mv5.14 -nle' / ( (.) (?: (?-2) | .? ) \g-1 ) (?{ say $1 }) (*FAIL) /xs '

Same, but using named subpatterns:

echo abABCDCBAdeXYZYXfg1221 | perl -Mv5.14 -nle' / ( (?&PALINDROME) ) (?{ say $1 }) (*FAIL) (?(DEFINE) (?<PALINDROME> (.) (?: (?&PALINDROME) | .? ) \g-1 ) ) /xs '

(*FAIL) is reached after finding and printing a palindrome. It forces a backtrack, which is to say it causes the engine to look for another palindrome.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11165956]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2026-03-08 23:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.