I would like to ask you for advice on writing a Perl module. We have three files.
(1) main.pl : uses my_function()
#!/usr/bin/perl
use strict;
use warnings;
use MyClass;
require "./subroutines.pl";
my $instance = MyClass->new({});
$instance->my_method("a");
MyClass::my_function("b"); # This works.
my_function("c"); # Undefined subroutine &main::my_function called
exit;
(2) MyClass.pm : defines MyClass class. my_method()
uses my_function()
which is defined in "subroutines.pl".
package MyClass;
use strict;
use warnings;
require "./subroutines.pl";
sub new {
my $class = shift;
my $self = shift;
return bless $self, $class;
}
sub my_method{
my $self = shift;
my $text = shift;
my_function($text);
}
1;
(3) subroutines.pl : defines my_function()
.
use strict;
use warnings;
sub my_function {
print "[$_[0]] My function is working!\n";
}
1;
The problem is that my_function()
is not working in main.pl, even though the source code has require "./subroutines.pl"
, while MyClass::my_function()
works.
[a] My function is working!
[b] My function is working!
Undefined subroutine &main::my_function called at main.pl line 11.
Because my_function()
is useful for me, I want to use it in both main.pl and MyClass.pm, but the subroutine is so general that it is quite strange to define it as a method in MyClass.pm. But it is also strange (to me) that we have to write MyClass::
before my_function()
, because the subroutine does not depend on MyClass
.
My question is: is it possible to modify the above codes so that my_function()
works in main.pl without adding MyClass::
before the function call?