Perl is scripting language; that means you don’t compile it to executable, like C/C++, nor compile it to binary file which executed by special environment, like Java of .Net Core. Instead you write a script which you feed to Perl interpreter, like a Bash of batch scripts.
Installing Perl very easy:
– for Unix use sudo apt-get install perl or sudo yum install perl
– for Windows there are two installers available here (don’t forget to enable setting up environment variable, or add it to the system PATH manually)
and on to our first Hello World:
print "Hello World from Perl!\n";
save it as hello.pl and execute with
perl hello.pl
On Unix you can add the first line which would tell what application (Perl in our case) to execute the script.
#!/usr/bin/env perl
print "Hello World from Perl!\n";
if you don’t have env program you can specify path directly:
#!/usr/bin/perl
print "Hello World from Perl!\n";
don’t forget to change file mode with chmod 755 hello.pl and now you can just run
./hello.pl
On Windows, file association with Perl interpreter usually works pretty well.
I would recommend start all script with those two lines:
use strict;
use warnings;
this would allow to catch many unwanted errors.
Let’s see somewhat real life scenario. Recently I found out that Vocabulary Builder doesn’t work on my Kindle Oasis if book format is mobi, but works fine if it’s azw3 format. So let’s write a script which would convert all mobi books in the current directory to awz3 format. To convert we will use Calibre:
use strict;
use warnings;
my $dir = '.';
my $converter = "C:\\Program Files (x86)\\Calibre2\\ebook-convert.exe";
opendir(DIR, $dir) or die $!;
while (my $mobi = readdir(DIR)) {
next unless (-f "$dir/$mobi");
next unless ($mobi =~ m/\.mobi$/);
my $azw3 = $mobi;
$azw3 =~ s/\.mobi$/\.azw3/;
print "converting $mobi to $azw3\n";
system $converter, $mobi, $azw3;
}
closedir(DIR);