title: Matching two overlapping patterns with Perl
body: <p>I hope that my question has not already been posed by someone else, since I tried to look almost everywhere in the site but I couldn't manage to find an answer.</p>
  
  <p>My problem is: I'm making a PERL script which has to detect the position of <strong>every occurrence</strong> of one <strong>or</strong> another pattern in a string.</p>
  
  <p>For instance:</p>
  
  <pre><code>$string = "betaalphabetabeta";
  $pattern = "beta|alpha";
  </code></pre>
  
  <p>In this case, I would like my script to return 4 matches.</p>
  
  <p>I thought that this could be easily achieved by using the match operator in someway like this:</p>
  
  <pre><code>$string =~ /beta|alpha/g;
  </code></pre>
  
  <p>However, since my two patterns ("alpha", "beta") are partially overlapping, the piece of code that I've just posted skips any occurrence of the first pattern when it overlaps with the second one.</p>
  
  <p>E.g. if I have a string like this one:</p>
  
  <pre><code>$string = "betalphabetabeta";
  </code></pre>
  
  <p>it only returns 3 matches instead of 4.</p>
  
  <p>I've tried to do something with the ?= operator, but I can't manage to couple it with the OR operator in a correct way... </p>
  
  <p>Does anyone have any solution? Thanks for your help!</p>