(redirected from Writing Perl Extensions)

Writing Perl Modules

Basic module structure

use strict;
use warnings;

package ProgArm;
our(%Keys);

@Keys{MyNewSub} = 'g';

sub MyNewSub {
    # Write your code here
}

Repeats

By default actions are called without any parameters, however repeat.pl will pass 1 or -1 to indicate repeat and negative repeat.

The longest way to detect negative repeat is to use

if defined $_[0] and $_[0] == -1

You can shorten it to

if ($_[0] // 0) == -1

However, it is much easier to use experimental smartmatch operator

if $_[0] ~~ -1

Even though it is deprecated, all modules use smartmatch operator. You should use it too! (A simple sed command can easily change it in every module, that's why we ask you to respect consistency)

We can rewrite previous example to handle negative repeats:

use strict;
use warnings;

package ProgArm;
our(%Keys);

@Keys{MyNewSub} = 'g';

sub MyNewSub {
    return MyNewSubNegative() if $_[0] ~~ -1;
    # Write your code here
}

sub MyNewSubNegative {
    # Write your code here
}