How to Make a Perl Script Work as a Module


or, how to make a perl module also runnable as a script. The title is closer to my intended purpose, which is to be able to write a script along with a full complement of tests externally in a second script.

foo: the actual script

    #!/usr/bin/perl -w
    main() unless caller();
    sub main {
        my $answer = 42;
        print "the answer is $answer\n";
        print "the square is ",foo::square($answer), "\n";
        print "the cube is ",foo::cube($answer), "\n";
    }
    package foo;
    sub square { $_ = shift; return($_ * $_); }
    sub cube   { $_ = shift; return($_ * $_ * $_); }
    1;

foo.t: the "testing" script

    #!/usr/bin/perl -w
    require "foo";
    print   "numbers:  ";
    foreach (1..10) { printf("%5d ", foo::square($_)); }
    print "\nsquares:  ";
    foreach (1..10) { printf("%5d ", foo::square($_)); }
    print "\ncubes:    ";
    foreach (1..10) { printf("%5d ", foo::cube($_)); }
    print "\n";

output

    $ ./foo
    the answer is 42
    the square is 1764
    the cube is 74088
    $ ./foo.t
    numbers:      1     4     9    16    25    36    49    64    81   100
    squares:      1     4     9    16    25    36    49    64    81   100
    cubes:        1     8    27    64   125   216   343   512   729  1000
    $


source: various, I got the idea about a year ago from use Perl
keywords: perl
date: 02/18/2005