Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a .pl file

Tags:

import

perl

I was wondering how to import a Perl file to a script. I experimented with use, require and do, but nothing seems to work for me. This is how I did it with require:

#!/usr/bin/perl

require {
 (equations)
}

print "$x1\n";

Is it possible to code for substituting a value (I get in my script) into equations.pl, then have my script use an equation defined in equations.pl to calculate another value? How do I do this?

like image 999
Nina Avatar asked Oct 20 '25 14:10

Nina


2 Answers

You can require a .pl file, which will then execute the code in it, but in order to access variables, you need a package, and either "use" instead of require (the easy way) or via Exporter.

http://perldoc.perl.org/perlmod.html

Simple example: here's the stuff you want to import, name it Example.pm:

package Example;

our $X = 666;

1;  # packages need to return true.

And here's how to use it:

#!/usr/bin/perl -w
use strict;

use Example;

print $Example::X;

This presumes Example.pm is in the same directory, or the top level of an @INC directory.

like image 161
CodeClown42 Avatar answered Oct 22 '25 09:10

CodeClown42


equations.pm file:

package equations;

sub add_numbers {
  my @num = @_;
  my $total = 0;
  $total += $_ for @num;
  $total;
}

1;

test.pl file:

#!/usr/bin/perl -w

use strict;
use equations;

print equations::add_numbers(1, 2), "\n";

output:

3
like image 35
Ωmega Avatar answered Oct 22 '25 09:10

Ωmega