The reason this smelled so of homework is that many instructors love these tricky regex puzzles. "Do <whatever> with a single regex" whether or not that is a sane thing to do. Most such problems are better solved with several regexen or other constructs, all pasted together with a bit of logic.

Your problems each consist of two distinct logical requirements.

  1. An alphabet, and
  2. A condition on the number of certain substrings.
The first is most easily handled with a negative binding of a negated character class.
sub is_abc { local $_ = shift || $_; $_ !~ /[^abc]/ } sub is_ab { local $_ = shift || $_; $_ !~ /[^ab]/ }
Those subs could easily be autoloaded.

The arithmetic tests differ, and their best implementation may or may not involve a regex match. The odd number of ab pairs is easily implemented with a global one, together with bitwise &,

sub has_odd_ab { local $_ = shift || $_; my $n = () = /ab/g; # count matches 1 & $n # odd? }
The condition for the second problem is better done with tr///, because it is quicker for counting individual characters. However it looks, tr/// is not really a regex solution. The logical or appearing in the condition allows a tidy way to package those conditions.
sub odd_a { local $_ = shift || $_; 1 & tr/a//; } sub odd_b { local $_ = shift || $_; 1 & tr/b//; }
and the solutions,
sub prob_one { local $_ = shift || $_; is_abc and has_odd_ab; } sub prob_two { local $_ = shift || $_; is_ab and ! odd_a or odd_b; }
All that localizing of $_ is to allow $_ to be the default argument without causing any modifications to it.

After Compline,
Zaxo


In reply to Re: Regex Homework by Zaxo
in thread Regex Homework by chuleto1

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.