Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How to convert Perl file to a perl module(.pm file).

by tobyink (Canon)
on Nov 02, 2012 at 15:32 UTC ( [id://1001998]=note: print w/replies, xml ) Need Help??


in reply to How to convert Perl file to a perl module(.pm file).

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'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1001998]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2024-04-24 21:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found