To make your module export variables and/or functions like a "real" module, use the Exporter module.
package MySequence;
#file: MySequence.pm
use strict;
use base 'Exporter';
our @EXPORT = qw(reversec seqlen);
our @EXPORT_OK = qw($EcoRI);
our $EcoRI = 'ggatcc';
sub reversec {
my $sequence = shift;
$sequence = reverse $sequence;
$sequence =~ tr/gatcGATC/ctagCTAG/;
return $sequence;
}
sub seqlen {
my $sequence = shift;
$sequence =~ s/[^gatcnGATCN]//g;
return length $sequence;
}
1; |
The use base 'Exporter' line tells Perl that this module is a type of "Exporter" module. As we will see later, this is a way for modules to inherit properties from other modules. The Exporter module (standard in Perl) knows how to export variables and functions.
The our @EXPORT = qw(reversec seqlen) line tells Perl to export the functions reversec and seqlen automatically. The our @EXPORT_OK = qw($EcoRI) tells Perl that it is OK for the user to import the $EcoRI variable, but not to export it automatically.
The qw() notation is telling Perl to create a list separated by spaces. These lines are equivalent to the slightly uglier:
our @EXPORT = ('reversec','seqlen');
Now the module exports its reversec and seqlen functions automatically:
#!/usr/bin/perl #file: sequence2.pl use strict; use MySequence; my $sequence = 'gattccggatttccaaagggttcccaatttggg'; my $complement = reversec($sequence); print "original = $sequence\n"; print "complement = $complement\n"; |
The calling program can also get at the value of the $EcoRI variable, but he has to ask for it explicitly:
#!/usr/bin/perl
#file: sequence3.pl
use strict;
use MySequence qw(:DEFAULT $EcoRI);
my $sequence = 'gattccggatttccaaagggttcccaatttggg';
my $complement = reversec($sequence);
print "original = $sequence\n";
print "complement = $complement\n";
if ($complement =~ /$EcoRI/) {
print "Contains an EcoRI site.\n";
} else {
print "Doesn't contain an EcoRI site.\n";
}
|
Note that we must now import the :DEFAULT group in order to get the default reversec and seqlen functions.
|
| Contents |
Next |