Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a file core.pm which is a pl file. How do I convert it to core.pm(perl module)

  • Comment on How to convert Perl file to a perl module(.pm file).

Replies are listed 'Best First'.
Re: How to convert Perl file to a perl module(.pm file).
by tobyink (Canon) on Nov 02, 2012 at 15:32 UTC

    The trivial answer is to just rename it, and make sure it returns a true value (this is usually done by making sure the last line of code is "1;").

    More generally you probably want to:

    • Move any functionality that is not already wrapped in sub {...} into subs, allowing the subs to be triggered explicitly by the caller.

    • Factor out any use of input from STDIN and output to STDOUT, so that instead it gets its input from the caller script, and returns its output to the caller via function calls.

    Here's an example script...

    # greeting.pl print "What is your name?\n"; chomp(my $name = <STDIN>); print "Hello, $name!\n";

    You could refactor it into a module like this:

    # Greeting.pm package Greeting; sub say_text { my $handle = shift; print $handle "$_\n" for @_; } sub read_answer { my $handle = shift; chomp(my $answer = <$handle>); return $answer; } sub question { return "What is your name?"; } sub response { my $name = shift; return "Hello $name"; } 1;

    Which could be used like this...

    # greeting.pl use Greeting; my $in = \*STDIN; my $out = \*STDOUT; Greeting::say_text($out, Greeting::question()); my $name = Greeting::read_answer($in); Greeting::say_text($out, Greeting::response($name));

    After that, something to consider is making your code more object-oriented, thus allowing people to subclass it, overriding parts of its functionality.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: How to convert Perl file to a perl module(.pm file).
by MidLifeXis (Monsignor) on Nov 02, 2012 at 15:23 UTC
Re: How to convert Perl file to a perl module(.pm file).
by Anonymous Monk on Nov 02, 2012 at 16:29 UTC
    No you don't. Read the INSTALL file and follow the instructions.