Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl prototype subroutine in class

I am trying to call a prototype function from a class without instantiating an object. An example of my class MyClass :

package MyClass;
use strict;
use warnings;

sub import{
        my $class = shift;
        my ($caller) = caller();
        eval "sub ${caller}::myprot(\&);";
        eval "*${caller}::myprot = \&MyClass::myprot;";        
}

sub myprot (&) {
    my ($f) = @_;
        $f->();
}

1;

I want to call the prototype from a script main.pl:

use strict;
use warnings;

use MyClass;

myprot {
        print "myprot\n";
};

and I am getting the errors:

Use of uninitialized value in subroutine entry at MyClass.pm line 14.
Use of uninitialized value in subroutine entry at MyClass.pm line 14.
Undefined subroutine &main::myprot called at main.pm line 8.

I don't really understand the undefined subroutine error: With use, import is called which defines the prototype for main.pl. I also really don't understand the uninitialised value error. I'd be happy for some explanation.

like image 826
user1981275 Avatar asked Sep 15 '26 15:09

user1981275


1 Answers

You're looking for Exporter.

package MyClass;
use strict;
use warnings;

use Exporter qw( import );

our @EXPORT = qw( myprot );

sub myprot(&) {
    my ($f) = @_;
    $f->();
}

1;

I usually use @EXPORT_OK (requiring the use of use MyClass qw( myprot );) rather than exporting by default.

like image 120
ikegami Avatar answered Sep 17 '26 14:09

ikegami