1

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?

H. Shindoh
  • 906
  • 9
  • 23

1 Answers1

3

require only executes a given file once, so you would need do, but that would created two copies of the subroutine. Use a proper module instead, and use Exporter to export the symbol.

Subroutines.pm:

package Subroutines;

use strict;
use warnings;

use Exporter qw( import );
our @EXPORT = qw( my_function );

sub my_function {
  print "[$_[0]] My function is working!\n";
}

1;

and

use Subroutines;
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Thank you for your answer. I thought that *.pm was only for classes. – H. Shindoh Aug 31 '15 at 14:54
  • 1
    It's for modules, whether they classes or not. I discussed the Perl-related file types [here](http://stackoverflow.com/questions/6376006/what-is-the-difference-between-library-files-and-modules/6379109#6379109) – ikegami Aug 31 '15 at 15:00
  • Oops, the `package` directive was missing. Added. – ikegami Aug 31 '15 at 15:50