The weekly challenge 280 - Task 1: Twice Appearance

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-280/#TASK1
 3 #
 4 # Task 1: Twice Appearance
 5 # ========================
 6 #
 7 # You are given a string, $str, containing lowercase English letters only.
 8 #
 9 # Write a script to print the first letter that appears twice.
10 #
11 ## Example 1
12 ##
13 ## Input: $str = "acbddbca"
14 ## Output: "d"
15 #
16 ## Example 2
17 ##
18 ## Input: $str = "abccd"
19 ## Output: "c"
20 #
21 ## Example 3
22 ##
23 ## Input: $str = "abcdabbb"
24 ## Output: "a"
25 #
26 ############################################################
27 ##
28 ## discussion
29 ##
30 ############################################################
31 #
32 # Read one character at a time, and return it if it was already
33 # in the string before.
34 
35 use strict;
36 use warnings;
37 
38 twice_appearance("acbddbca");
39 twice_appearance("abccd");
40 twice_appearance("abcdabbb");
41 
42 sub twice_appearance {
43    my $str = shift;
44    my $seen = {};
45    print "Input: \"$str\"\n";
46    foreach my $char (split //, $str) {
47       return print "Output: $char\n" if $seen->{$char};
48       $seen->{$char} = 1;
49    }
50    print "Output: None\n";
51 }