Counting the stars
Weekly challenge 280 — 29 July 2024
Week 280: 29 Jul 2024
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.
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"
Again, there's probably a one-liner, but I simply:
|.*?|
*
... which only leaves the countable asterisks, and
the answer is therefore length($str)
.
#!/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)); }
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