Peter’s blog ✴ Week 273 ✴ 10 June 2024

THE WEEKLY CHALLENGE
All about characters

The Perl Camel

Task 2

B after A

You are given a string, $str. Write a script to return true if there is at least one b, and no a appears after the first b.

Examples


Example 1
Input: $str = "aabb"
Output: true

Example 2
Input: $str = "abab"
Output: false

Example 3
Input: $str = "aaa"
Output: false

Example 4
Input: $str = "bbb"
Output: true

Analysis

This is an easy one-liner:

($str =~ m|b(.*)| and $1 =~ m|^[^a]*$|) ? 
   'true' : 'false'

The first regular expression - $str =~ m|b(.*)| - looks for a 'b' and the second - $1 =~ m|^[^a]*$| - checks for no 'a' in the part of the string follwing the first 'b': note that the $1 refers to the matched substring from the first regular expression.

Perl Weekly’s review

from PW issue 673

Perl pure regex implementation to deal with both tasks. Don't forget to try DIY tool.

Try it 

Try running the script with any input:



example: aardvarks live in burrows

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-06-10
use utf8;     # Week 273 - task 2 - B after a
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

b_after_a('aabb');
b_after_a('abab');
b_after_a('aaa');
b_after_a('bbb');
b_after_a('ccc');
b_after_a('Write a script to return true if there is at least one b');

sub b_after_a {
    
    my $str = $_[0];
    
    # match a 'b', and then match no 'a' in the rest of the string
    say qq[\nInput:  \$str = '$str'];
    say qq[Output: ] . (($str =~ m|b(.*)| and $1 =~ m|^[^a]*$|) ? 'true' : 'false');
}

4 lines of code

Output from script


Input:  $str = 'aabb'
Output: true

Input:  $str = 'abab'
Output: false

Input:  $str = 'aaa'
Output: false

Input:  $str = 'bbb'
Output: true

Input:  $str = 'ccc'
Output: false

Input:  $str = 'Write a script to return true if there 
   is at least one b'
Output: true

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain