Peter’s blog ✴ Week 280 ✴ 29 July 2024

THE WEEKLY CHALLENGE
Counting the stars

The Perl Camel

Task 2

Count asterisks

You are given a string, $str, where every two consecutive vertical bars are grouped into a pair. Write a script to return the number of asterisks, *, excluding any between each pair of vertical bars.

Examples


Example 1
Input: $str = "p|*e*rl|w**e|*ekly|"
Output: 2
The characters we are looking for here are "p" 
   and "w**e".

Example 2
Input: $str = "perl"
Output: 0

Example 3
Input: $str = "th|ewe|e**|k|l***ych|alleng|e"
Output: 5
The characters we are looking for here are "th", 
   "e**", "l***ych" and "e"

Analysis

Again, there's probably a one-liner, but I simply:

  • removed everything that matches |.*?|
  • removed all characters which are not *

... which only leaves the countable asterisks, and the answer is therefore length($str).

Perl Weekly’s review

from PW issue 680

Interesting use of regex and we have pretty cool solutions in Perl. Thanks for sharing knowledge with us.

Try it 

Try running the script with any input:



example: ***|***|***

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-07-29
use utf8;     # Week 280 - task 2 - Count asterisks
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

count_asterisks('p|*e*rl|w**e|*ekly|');
count_asterisks('perl');
count_asterisks('th|ewe|e**|k|l***ych|alleng|e');
count_asterisks('*****|*****|*****|*****|');

sub count_asterisks {
    
    my ($str);
    
    $str = shift @_;
    printf(qq[\nInput:  \@str = '%s'\n], $str);

    # remove |.*?| from $str
    $str =~ s/\|.*?\|//g;
    
    # remove non * from $str
    $str =~ s|[^\*]||g;
    
    printf(qq[Output: %s\n], length($str));
}

7 lines of code

Output from script


Input:  @str = 'p|*e*rl|w**e|*ekly|'
Output: 2

Input:  @str = 'perl'
Output: 0

Input:  @str = 'th|ewe|e**|k|l***ych|alleng|e'
Output: 5

Input:  @str = '*****|*****|*****|*****|'
Output: 10

 

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