aoiee aoiee - 1 year ago 76
Perl Question

Make a Perl object callable?

In Perl 5, is there a way to make an object callable?

Example.pm

package Example;
use strict;
use warnings;
sub new {
my ($class) = @_;
my $self = {};
bless($self, $class);
return $self;
}

# implement function to make class callable

1;


main.pl

use Example;
my $ex = Example->new();
my $ex(); # call the object like this

Answer Source

This can be done by blessing a function reference instead of a hash reference to create the class.

For example:

Example.pm:

package Example;
use strict;
use warnings;
sub new {
    my ($class) = @_;
    my $self = \&call;
    bless($self, $class);
    return $self;
}

# implement function to make class callable
sub call {
    print "Calling the function\n";
}

1;

main.pl:

use strict;
use warnings;
use Example;

my $ex = Example->new();
$ex->();

Output:

Calling the function

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download