The weekly challenge 280 - Task 2: Count Asterisks
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-280/#TASK2 3 # 4 # Task 2: Count Asterisks 5 # ======================= 6 # 7 # You are given a string, $str, where every two consecutive vertical bars are 8 # grouped into a pair. 9 # 10 # Write a script to return the number of asterisks, *, excluding any between 11 # each pair of vertical bars. 12 # 13 ## Example 1 14 ## 15 ## Input: $str = "p|*e*rl|w**e|*ekly|" 16 ## Ouput: 2 17 ## 18 ## The characters we are looking here are "p" and "w**e". 19 # 20 ## Example 2 21 ## 22 ## Input: $str = "perl" 23 ## Ouput: 0 24 # 25 ## Example 3 26 ## 27 ## Input: $str = "th|ewe|e**|k|l***ych|alleng|e" 28 ## Ouput: 5 29 ## 30 ## The characters we are looking here are "th", "e**", "l***ych" and "e". 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # Split $str at | characters, and then only look at the odd 39 # ones. Split those into single characters and count the stars. 40 41 use strict; 42 use warnings; 43 44 count_asterisks("p|*e*rl|w**e|*ekly|"); 45 count_asterisks("perl"); 46 count_asterisks("th|ewe|e**|k|l***ych|alleng|e"); 47 48 sub count_asterisks { 49 my $str = shift; 50 my @parts = split /\|/, $str; 51 my $index = 0; 52 my $count = 0; 53 print "Input: \"$str\"\n"; 54 foreach my $part (@parts) { 55 $index++; 56 next unless $index % 2; 57 foreach my $char (split //, $part) { 58 $count++ if $char eq '*'; 59 } 60 } 61 print "Output: $count\n"; 62 }