Let’s create Morse Code using PERL

Mazhar Ahmed
The Devs Tech
Published in
2 min readJul 30, 2020
Image taken from Reddit

At the beginning of this article, we have two questions:
1) What is Morse Code
2) Why PERL!

Morse code is a method used in telecommunication to encode text characters as standardized sequences of two different signal durations, called dots and dashes or dits and dahs. Morse code is named after Samuel Morse, an inventor of the telegraph.

I want to use PERL because it comes built in with every Linux and Mac. I can just use the program without installing anything. Also PERL has a wide variety of features when we wanna handle string operations. PERL is a highly capable, feature-rich programming language with over 30 years of development. Years ago PERL 6 is released and soon after it’s renamed to Raku. Here, I’ll be using PERL 5 which comes built-in with all linux and mac.

You can find the list of Morse Code here http://www.sckans.edu/~sireland/radio/code.html
Also you can learn it here http://www.learnmorsecode.com

First let’s create an array with the code like:

# morse code list
my %letters;
# First digits
$letters{'0'} = '-----';
$letters{'1'} = '.----';
$letters{'2'} = '..---';
$letters{'3'} = '...--';
$letters{'4'} = '....-';
$letters{'5'} = '....';
$letters{'6'} = '-....';
$letters{'7'} = '--...';
$letters{'8'} = '---..';
$letters{'9'} = '----.';
# And now, letters
$letters{'A'} = '.-';
$letters{'B'} = '-..';
$letters{'C'} = '-.-.';
$letters{'D'} = '-..';
$letters{'E'} = '.';
$letters{'F'} = '..-.';
$letters{'G'} = '--.';
$letters{'H'} = '....';
$letters{'I'} = '..';
$letters{'J'} = '.---';
$letters{'K'} = '-.-';
$letters{'L'} = '.-..';
$letters{'M'} = '--';
$letters{'N'} = '-.';
$letters{'O'} = '---';
$letters{'P'} = '.--.';
$letters{'Q'} = '--.-';
$letters{'R'} = '.-.';
$letters{'S'} = '...';
$letters{'T'} = '-';
$letters{'U'} = '..-';
$letters{'V'} = '...-';
$letters{'W'} = '.--';
$letters{'X'} = '-..-';
$letters{'Y'} = '-.--';
$letters{'Z'} = '--..';
$letters{' '} = '/';

Now we can take a string and loop through it’s characters and make the morse code like:

$string = uc $string;for my $c (split //, $string) {
print $letters{$c}, " ";
}
print "\n";

I have created a gist here. You can save the gist file as morse.pl and execute it like

chmod +x morse.pl
./morse.pl "SOS Help"

And the output is like

... --- ... / .... . .-.. .--.

That’s it, that’s how we can convert our text to morse code. The next thing you can enhance like convert morse code to text and adding sound support etc.

Good Luck.

--

--