Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Regex Homework

by Zaxo (Archbishop)
on Feb 24, 2004 at 07:21 UTC ( [id://331344]=note: print w/replies, xml ) Need Help??


in reply to Regex Homework

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-25 07:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found