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.
Those subs could easily be autoloaded.sub is_abc { local $_ = shift || $_; $_ !~ /[^abc]/ } sub is_ab { local $_ = shift || $_; $_ !~ /[^ab]/ }
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 &,
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 has_odd_ab { local $_ = shift || $_; my $n = () = /ab/g; # count matches 1 & $n # odd? }
and the solutions,sub odd_a { local $_ = shift || $_; 1 & tr/a//; } sub odd_b { local $_ = shift || $_; 1 & tr/b//; }
All that localizing of $_ is to allow $_ to be the default argument without causing any modifications to it.sub prob_one { local $_ = shift || $_; is_abc and has_odd_ab; } sub prob_two { local $_ = shift || $_; is_ab and ! odd_a or odd_b; }
After Compline,
Zaxo
|
---|