blob: b8a9101c2a826eb8a21281e53598aae006887dfc (
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
|
#!/usr/bin/env perl
# ch-1.pl - Encode text into binary morse code
#
# Ryan Thompson <rjt@cpan.org>
use 5.010;
use warnings;
use autodie;
use strict;
use utf8;
no warnings 'uninitialized';
use Text::Trim;
# 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 %morse = morse_hash();
# Text from stdin or filenames specified on the command line
while ( $_ = <<>> ) {
trim;
s/\s+/ /; # Consolidate internal whitespace (and tabs) to single space
say join '', map { morse_bin($_) } split '';
}
# Return morse binary for a character
# See challenge description for the specification of this, but basically
# dot: 1, dash: 111, 0 in between dots/dashes, and 000 between each char
# Undefined characters return an empty string
sub morse_bin {
my $ch = shift;
my %map = ( '.' => '1', '-' => '111' );
return '0000' if $ch eq ' '; # Word separator, 7 0s but 3 from char sep
return '' if not exists $morse{$ch};
my $morse = join '0', map { $map{$_} } split '', $morse{$ch};
$morse . '000'; # Char separator
}
|