How do I include functions from another file in my Perl script?

Viewed 96902

This seems like a really simple question but somehow my Google-Fu failed me.

What's the syntax for including functions from other files in Perl? I'm looking for something like C's #include "blah.h"

I saw the option for using Perl modules, but that seems like it'll require a not-insignificant rewrite of my current code.

9 Answers

require is roughly equivalent to include. All of the namespace benefits can be achieved in a required perl script just like a perl module. The "magic" is in what you put in the script.

The only caveat to including a script is you need to return 1; at the end of the script, or perl says it failed, even if you haven't called anything in the script.

require "./trims.pl"

Then in your perl script it can be as simple as:

#!/usr/bin/perl

#use "trims.pl";


sub ltrim { my $s = shift; $s =~ s/^\s+//;       return $s };
sub rtrim { my $s = shift; $s =~ s/\s+$//;       return $s };
sub  trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
return 1;

This example removes white space from the left, right or both ends of the input string. $string = trim($string);

The comment of #use "trims.pl" can be pasted in your perl script, uncommented (remove the #) and perl will look in the same folder your script is in to find trims.pl and this puts the functions ltrim(), rtrim(), and trim() in the global name space, so you can't have those function names in any other global name space or perl will detect a conflict and stop the execution.

To learn more about controlling name spaces, look into "perl packages & modules" package Foo;

https://perldoc.perl.org/functions/package

Related