Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Answer: How do I place a subroutine in an external file and call it?

by bradcathey (Prior)
on Nov 04, 2003 at 01:20 UTC ( #304291=categorized answer: print w/replies, xml ) Need Help??

Q&A > subroutines > How do I place a subroutine in an external file and call it? - Answer contributed by bradcathey

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.

Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2016-10-26 10:04 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (338 votes). Check out past polls.