Searched for tag caller and found 1 results in 0.6 ms

Perl: A simple module that doubles as a script

I have a small Perl script that defines a handful of functions. Perl allows you to make a library that doubles as a script when called directly. Using caller() you can determine if your script was loaded via a require() call, or called directly. This allows you to export functions if called as a library, but run code if called directly via: perl my_lib.pl.

# my_lib.pl
if (!caller()) {
    say greet("Scott");
}

sub greet {
    my $name = shift();

    return "Hello $name";
}

1; # Required if you load as a library

Use a require() call to load the module and get access to the greet() function.

# main.pl
require("/path/my_lib.pl");

say greet("Foo");
Tags:
Leave A Reply