I have a function that I would like to define in two different Perl scripts, but dislike having to edit both. Is there a way I can include
it (like in PHP) from an external file?
FUNC FILE:
sub test {
}
FILE 1:
include func_file;
foo();
bar();
test();
FILE 2:
include func_file;
blah();
test();
variables / $@ $EVAL_ERROR $@ The Perl error from the last eval operator, i.e. the last exception that was caught. For eval BLOCK , this is either a runtime error message or the string or reference die was called with. The eval STRING form also catches syntax errors and other compile time exceptions.
A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" );
@ is used for an array. In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function: sub Average{ # Get total number of arguments passed. $ n = scalar(@_); $sum = 0; foreach $item (@_){ # foreach is like for loop...
To answer the question narrowly:
Yes, you can include a file by using the require('filename') function.
To answer the question generally:
Perl has a complete mechanism for defining and exporting functions through its package mechanism. This is described in perlmod. You should really use this mechanism, as you can eventually package up the module into a CPAN module, and make it available for others, or simply easy to install on other systems yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With