http://www.perlmonks.org?node_id=304291


in reply to How do I place a subroutine in an external file and call it?

We'll use the module model, and utilize the use Module protocol in the calling program. The alternative is to use require but Programming Perl (the blue Camel book), states that "In general, however, use is preferred over require because it looks for modules during complilation, so you learn about any mistakes sooner". Okay, here we go:

In the external file, or module, containing the subroutine:

  1. package the name of the module at the top (no shebang is needed)
  2. end your script with a true value, conventionally 1;
  3. save with initial uppercase letter and .pm extension

Here's the sample code for a module that validates user input for date and time (for untainting purposes):

package Validate; # use package to declare a module sub validate_date { my $val = shift; return() unless $val =~ /^(\d{2})-(\d{2})-(\d{4})$/; return "$3-$1-$2"; } sub validate_time { my $val = shift; return() unless $val =~ /^(\d{2}):(\d{2}) (am|pm)$/i; return uc("$1:$2 $3"); } 1;

In the calling program:

  1. declare the external file with use Module. The .pm and :: (double colons) are assumed by Perl.
  2. call the routine with Module::sub_name($variable_to_pass)

Here's the sample program that calls the Validate module:

#!/usr/bin/perl -w #would use -wT in production to check for taint print "Content-type: text/plain\n\n"; use strict; use CGI::Carp qw(fatalsToBrowser); # only for development use Validate; my $date = "12-01-2003"; my $time = "12:23 pm"; # would come from user input and so needs to +untainted my $valid_date = Validate::validate_date( $date ); if ( $valid_date ) { print "$valid_date is okay\n"; } else { print "$date is invalid\n"; } my $valid_time = Validate::validate_time( $time ); if ( $valid_time ) { print "$valid_time is okay\n"; } else { print "$time is invalid\n"; } exit;

For an object-oriented approach, checkout out bobn's comment.

Many thanks to The Mad Hatter, Roger, ysth.