aboutsummaryrefslogtreecommitdiff
path: root/challenge-035/ryan-thompson/perl5/ch-2.pl
blob: e271a5aca2f9619cec89ebd3e5dc0363600e2db5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env perl

# ch-2.pl - Read binary morse code
#
# Ryan Thompson <rjt@cpan.org>

use 5.016; # fc()
use warnings;
use autodie;
use strict;
use utf8;
no warnings 'uninitialized';

binmode STDOUT, ':utf8';

# Include the morse code table generated by ../extras/fetch-morse.pl
use lib qw< ../extras >;
eval { require 'morse_code.pl' };
die "Run fetch-morse.pl in ../extras first" if $@;
my %rmorse = reverse_morse( morse_hash() );


chomp, say morse_bin_to_utf8($_) while $_ = <<>>;


# Take morse binary and turn it (back) into utf8 text
sub morse_bin_to_utf8 {
    my $r = '';
    for (split /0{7}/, shift) {
        $r .= join '', map { $rmorse{$_} } split /000/;
        $r .= ' ';
    }

    $r;
}

# Reverse the morse hash. We could just use reverse(), but that would give
# inconsistent results for duplicate values. Plus we may as well convert
# the . and - to 1 and 0 at this stage.
sub reverse_morse {
    my %morse = @_;
    map {
        my $morse = $morse{$_};
        $morse =~ s/\./10/g;
        $morse =~ s/\-/1110/g;
        $morse =~ s/0$//; # Remove trailing intra-char gap

        $morse => fc $_
    } keys %morse;
}