Home » Howtos » Subroutines » Perl files |
You have a subroutine or collection of subroutines that you want to use in multiple Perl programs.
One solution is to put those subroutines into a separate file, for example one called common_functions.pl, and require
that file. But be aware that there are downsides to this technique, not the least of which is namespace collision. Have a look at creating your own module instead.
If you still want to examine require
, lets look at common_functions.pl:
sub add_ten($) { my ($number) = @_; return ($number + 10); } 1;
Note that you need the 1;
at the end of the file. This is because Perl needs the last expression in the file to return a true value.
In the program in which you want to call the subroutines, you need to require
common_functions.pl:
#!/usr/bin/perl use strict; use warnings; require 'common_functions.pl'; print "Enter a number: "; my $number = <>; chomp $number; print "Adding ten: " . add_ten($number) . "\n";
If the require file (common_functions.pl) is in another directory you will need to specify the absolute path:
require "/home/me/common_functions.pl";
You don't need to worry about recursive requiring (e.g. requiring a file that requires the current file), Perl will handle everything.
perldoc -f require perldoc -q require Chapter 2, Schwartz Randal L. "Perl Objects, References & Modules" O'Reilly 2003 perldoc perlmod perlfaq7 - How do I create a module perlootut - Object-Oriented Programming in Perl Tutorial