The Weekly Challenge - 280


TASK #1: Twice Appearance
You are given a string, $str, containing lowercase English letters only.

Write a script to print the first letter that appears twice.

#!/usr/bin/perl
use strict;
use warnings;

sub twice_appearance {
    
    my %found = ();

    foreach my $char ( split(//, $_[0]) ) {
        return($char) if ($found{$char});
        $found{$char} = 1;
    }
    # return -1 if no duplicate is found
    return(-1);  
}

# Tests

my $str;

# Example 1
$str = "acbddbca";
print(twice_appearance($str), "\n"); # Output: "d"

# Example 2
$str = "abccd";
print(twice_appearance($str), "\n"); # Output: "c"

# Example 3
$str = "abcdabbb";
print(twice_appearance($str), "\n"); # Output: "a"

# Study: https://reiniermaliepaard.nl/perl/part-2/index.php?id=useful_hash

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.
#!/usr/bin/perl
use strict;
use warnings;

sub count_asterisks {

    # Remove the content within each pair of vertical bars
    $_[0] =~ s/\|[^|]*\|//g;

    # Count the remaining asterisks
    # see 11.3 on https://reiniermaliepaard.nl/perl/part-1/index.php?id=transliteration
    return( $_[0] =~ tr/*/*/ );
}

# Tests

my $str;

# Example 1
$str = "p|*e*rl|w**e|*ekly|";
print(count_asterisks($str), "\n"); # Output: 2

# Example 2
$str = "perl";
print(count_asterisks($str), "\n"); # Output: 0

# Example 3
$str = "th|ewe|e**|k|l***ych|alleng|e";
print(count_asterisks($str), "\n"); # Output: 5