Lightweight object-​oriented Perl scripts: From modulinos to moodulinos

Last week I found myself devel­op­ing a Perl script to cat­a­log some infor­ma­tion for our qual­i­ty assur­ance team. Unfortunately, as these things some­times do, the scrip­t’s com­plex­i­ty and require­ments start­ed increas­ing. I still want­ed to keep it as a sim­ple script. Yet, it was grow­ing com­mand line argu­ments that need­ed extra val­i­da­tion. I also need­ed to test some func­tions with­out wait­ing for the entire script to run.

As with many things Perl, the basic solu­tion is fair­ly old. Over twen­ty years ago, bri­an d foy pop­u­lar­ized the mod­uli­no pat­tern. in which Perl scripts that you exe­cute from the com­mand line can also act as Perl mod­ules. You can even usethese mod­ules in oth­er con­texts, for exam­ple test­ing.*A mod­uli­no seemed like the per­fect solu­tion for test­ing indi­vid­ual script func­tions, but writ­ing object-​oriented Perl out­side of a frame­work (or the new Perl class syn­tax) can be chal­leng­ing and verbose.

Enter the cow (Moo)

The Moo sys­tem of mod­ulesare billed as a light­weight way ​“to con­cise­ly define objects and roles with a con­ve­nient syn­tax that avoids the details of Perl’s object sys­tem.” It does­n’t have any XS code. Thus, it does­n’t need a C com­pil­er to install. Unlike its inspi­ra­tion, Moose, it’s opti­mized for the fast start­up time need­ed for a command-​line script. Sure, you don’t get a full-​strength meta-​object pro­to­col for query­ing and manip­u­lat­ing class­es, objects, and attributes—those capa­bil­i­ties are con­cerns for larg­er appli­ca­tions or libraries. In keep­ing with the light­weight theme, you can use Type::Tinycon­straints for para­me­ter val­i­da­tion. Additionally, there are sev­er­al solu­tions for turn­ing command-​line argu­ments into object attrib­ut­es. (I chose to use MooX::Options, main­ly because of its easy avail­abil­i­ty as an Ubuntu Linux pack­age.)

I’m not about to dump a pro­pri­etary script here on my blog. Yet, I haveworked up an illus­tra­tive exam­ple of how to incor­po­rate Moo into a mod­uli­no. Call it a ​“mooduli­no” if you like; here’s a short-​ish script to tell Perl just how you feel at this time of day:

#!/usr/bin/env perl

use v5.38;

package moodulino;
use Moo;
use MooX::Options;
use Types::Standard qw(ArrayRef Str);

option name => (
    is       => 'ro',
    isa      => Str,
    required => 1,
    short    => 'n',
    doc      => 'your name here',
    format   => 's',
);

option moods => (
    is        => 'ro',
    isa       => ArrayRef [Str],
    predicate => 1,
    short     => 'm',
    doc       => 'a list of how you might feel',
    format    => 's@',
    autosplit => ',',
);

has time_of_day => (
    is      => 'ro',
    isa     => Str,
    builder => 1,
);

sub _build_time_of_day ($self) {
    my %hours = (
         5 => ‘morning’,
        12 => 'afternoon',
        17 => 'evening',
        21 => 'night',
    );

    for ( sort { $b <=> $a } keys %hours ) {
        return $hours{$_} if (localtime)[2] >= $_;
    }
    return 'night';
}

sub run ($self) {
    printf "Good %s, %s!\n",
      $self->time_of_day,
      $self->name;

    if ( $self->has_moods ) {
        say 'How are you feeling?';
        say "- $_?" for $self->moods->@*;
    }
}

package main;

main() unless caller;

sub main { moodulino->new_with_options->run() }

And here’s what hap­pens when I run it:

% chmod a+x moodulino.pm
% ./moodulino.pm
name is missing
USAGE: moodulino.pm [-h] [long options ...]

    -m --moods=[Strings]  a list of how you might feel
    -n --name=String      your name here

    --usage               show a short help message
    -h                    show a compact help message
    --help                show a long help message
    --man                 show the manual
% ./moodulino.pm --name Mark
Good afternoon, Mark!
% ./moodulino.pm —name Mark --moods happy --moods sad --moods excited
Good afternoon, Mark!
How are you feeling?
- happy?
- sad?
- excited?
% ./moodulino.pm —name Mark --moods happy,sad,excited
Good afternoon, Mark!
How are you feeling?
- happy?
- sad?
- excited?

If the mood strikes, I can even write a test script for my script:

#!/usr/bin/env perl

use v5.38;
use Test2::V0;
use moodulino;

plan(3);

my $mood = moodulino->new( name => 'Bessy' );
isa_ok( $mood, 'moodulino' );
can_ok( $mood, 'time_of_day' );

is( $mood->time_of_day,
    in_set( qw(
        morning
        afternoon
        evening
        night
    ) ) );

And run it:

% prove -I. t/time_of_day.t
t/daytime.t .. ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.00 usr  0.00 sys +  0.07 cusr  0.01 csys =  0.08 CPU)
Result: PASS

* foy lat­er expand­ed this idea into the chap­ter ​“Modules as Programs” in Mastering Perl (2007). You can also read more in his 2014 arti­cle ​“Rescue lega­cy code with mod­uli­nos”. Also explore Gábor Szabó’s arti­cleson the top­ic. ↩︎


Discover more from The Phoenix Trap

Subscribe to get the latest posts sent to your email.

Mark Gardner Avatar

Hi, I’m Mark.

Hi, I’m Mark Gard­ner, and this is my personal blog. I show software developers how to level up by building production-ready things that work. Clear code, real projects, lessons learned.

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.