TExcelTAD
Home › Perl › Core Modules Tour

Core Modules Tour

Perl's standard distribution includes hundreds of core modules: they are available wherever Perl is installed, no CPAN download needed. This lesson is a quick tour of the ones you will reach for most often. perldoc Module::Name shows the full documentation of each.

Module What it gives you
List::Util sum, max, min, first, reduce, any, all, uniq, pairs, shuffle
Scalar::Util blessed, reftype, looks_like_number, weaken, dualvar
POSIX floor, ceil, fmod, strftime, INT_MAX and other C library functions
Time::Local timelocal, timegm: date parts back to an epoch number
Data::Dumper print any data structure as Perl code
Storable dclone deep copies, store/retrieve to files
JSON::PP encode and decode JSON
File::Basename, File::Spec portable path handling
Getopt::Long command-line option parsing
Text::Wrap wrap long text to a given width
Digest::MD5, Digest::SHA, MIME::Base64 hashes and encodings

List::Util in depth

perl · try it yourself
use strict;
use warnings;
use List::Util qw(reduce any all none sum0 product pairs pairmap maxstr);

my @scores = (8, 3, 10, 6);

my $max = reduce { $a > $b ? $a : $b } @scores;
my $csv = reduce { "$a,$b" } @scores;
print "reduce max: $max, joined: $csv\n";
print "any > 9: ", (any { $_ > 9 } @scores) ? "yes" : "no", "\n";
print "all > 2: ", (all { $_ > 2 } @scores) ? "yes" : "no", "\n";
print "product: ", product(@scores), ", sum0(): ", sum0(), "\n";
print "longest-sorting word: ", maxstr(qw(apple pear zucchini)), "\n";

my @kv = (a => 1, b => 2, c => 3);
print "pairs: ", join(" ", map { "$_->[0]:$_->[1]" } pairs @kv), "\n";
print "pairmap: ", join(" ", pairmap { "$a=" . $b * 10 } @kv), "\n";
reduce max: 10, joined: 8,3,10,6
any > 9: yes
all > 2: yes
product: 1440, sum0(): 0
longest-sorting word: zucchini
pairs: a:1 b:2 c:3
pairmap: a=10 b=20 c=30

reduce repeatedly combines $a (the result so far) with $b (the next element). maxstr returns the string that sorts last, not the longest one.

Dates: POSIX::strftime and Time::Local

Dates are full of pitfalls; work in UTC with gmtime and timegm for repeatable results. strftime formats a broken-down time:

perl · try it yourself
use strict;
use warnings;
use POSIX qw(strftime);
use Time::Local qw(timegm);

my $epoch = timegm(0, 30, 14, 15, 6 - 1, 2024);   # 2024-06-15 14:30:00 UTC (month is 0-based)
print "Epoch seconds: $epoch\n";
print strftime("%Y-%m-%d %H:%M:%S", gmtime $epoch), "\n";
print strftime("%A, %d %B %Y", gmtime $epoch), "\n";

my $week_later = $epoch + 7 * 24 * 60 * 60;
print "One week later: ", strftime("%Y-%m-%d (%a)", gmtime $week_later), "\n";

my $days = (timegm(0, 0, 0, 25, 11, 2024) - timegm(0, 0, 0, 15, 5, 2024)) / 86400;
print "Days from June 15 to Dec 25: $days\n";
Epoch seconds: 1718461800
2024-06-15 14:30:00
Saturday, 15 June 2024
One week later: 2024-06-22 (Sat)
Days from June 15 to Dec 25: 193

JSON::PP

JSON::PP reads and writes JSON. canonical sorts hash keys so the output is stable, and pretty indents it:

perl · try it yourself
use strict;
use warnings;
use JSON::PP;

my $json = JSON::PP->new->canonical;

my $data = $json->decode('{"name":"Ada","langs":["perl","c"],"active":true}');
print "Name: $data->{name}\n";
print "Second language: $data->{langs}[1]\n";
print "Active: ", ($data->{active} ? "yes" : "no"), "\n";

$data->{langs} = [ sort @{ $data->{langs} } ];
$data->{year} = 1843;
print $json->encode($data), "\n";
print JSON::PP->new->canonical->pretty->encode({ ok => JSON::PP::true, ids => [1, 2] });
Name: Ada
Second language: c
Active: yes
{"active":true,"langs":["c","perl"],"name":"Ada","year":1843}
{
   "ids" : [
      1,
      2
   ],
   "ok" : true
}

Paths: File::Basename and File::Spec

perl · try it yourself
use strict;
use warnings;
use File::Basename qw(basename dirname fileparse);
use File::Spec;

my $path = "/srv/www/site/images/logo.final.png";
print "basename: ", basename($path), "\n";
print "dirname:  ", dirname($path), "\n";

my ($name, $dir, $ext) = fileparse($path, qr/\.[^.]*$/);
print "name=$name dir=$dir ext=$ext\n";

print "joined: ", File::Spec->catfile("srv", "logs", "app.log"), "\n";
basename: logo.final.png
dirname:  /srv/www/site/images
name=logo.final dir=/srv/www/site/images/ ext=.png
joined: srv/logs/app.log

Command-line options: Getopt::Long

Scripts read their arguments from @ARGV. Getopt::Long turns options like --verbose --name=Kim -n 3 into variables. Here @ARGV is set by hand to simulate a command line:

perl · try it yourself
use strict;
use warnings;
use Getopt::Long qw(GetOptionsFromArray);

my @args = ("--name=Kim", "--verbose", "-n", "3", "--tag", "a", "--tag", "b", "report.txt");

my %opt = (count => 1, verbose => 0);
my @tags;
GetOptionsFromArray(\@args,
    "name=s"    => \$opt{name},       # =s takes a string
    "n|count=i" => \$opt{count},      # =i takes an integer; -n is an alias
    "verbose!"  => \$opt{verbose},    # flag; also accepts --noverbose
    "tag=s"     => \@tags,            # may repeat
) or die "Bad options\n";

print "name=$opt{name} count=$opt{count} verbose=$opt{verbose}\n";
print "tags=@tags\n";
print "remaining arguments: @args\n";
name=Kim count=3 verbose=1
tags=a b
remaining arguments: report.txt

In a real script you would call GetOptions(...), which works on @ARGV directly.

Text, digests and deep copies

perl · try it yourself
use strict;
use warnings;
use Text::Wrap qw(wrap $columns);
use Digest::MD5 qw(md5_hex);
use MIME::Base64 qw(encode_base64);
use Storable qw(dclone);

$columns = 30;
print wrap("", "  ", "Perl ships with a large standard library, so many everyday tasks need no extra downloads at all."), "\n";

print "md5: ", md5_hex("hello"), "\n";
print "base64: ", encode_base64("Perl rocks", ""), "\n";

my $orig = { list => [1, 2] };
my $copy = dclone($orig);
push @{ $copy->{list} }, 3;
print "original: @{ $orig->{list} }, copy: @{ $copy->{list} }\n";
Perl ships with a large
  standard library, so many
  everyday tasks need no
  extra downloads at all.
md5: 5d41402abc4b2a76b9719d911017c592
base64: UGVybCByb2Nrcw==
original: 1 2, copy: 1 2 3

Test yourself

Which module provides strftime?

  1. List::Util
  2. POSIX
  3. Time::Local
  4. Data::Dumper

Why use JSON::PP->new->canonical?

  1. To validate JSON
  2. To sort hash keys so output is stable
  3. To make it faster
  4. To allow comments

What does reduce { $a + $b } 1, 2, 3, 4 return?

  1. 4
  2. 10
  3. 24
  4. (1, 3, 6, 10)