Dynamic function?

H

howa

Hello,

Is it possible to wrap a non-extistence function of an object, to
another function?

E.g.

package Test;

sub new {

my ( $class ) = @_;

my $self = undef;
bless $self, $class;
return $self;
}

sub call {
my ($self, $fn) = @_;

print $fn . " is called ";
}

1;

my $obj = Test->new();

$obj->foo(a,b,c)
# will become $obj->call("foo", a, b, c);

$obj->bar(d,e,f);
# will become $obj->call("bar", d, e, f);


Thanks.
 
J

Jens Thoms Toerring

howa said:
Is it possible to wrap a non-extistence function of an object, to
another function?

package Test;
sub new {
my ( $class ) = @_;
my $self = undef;
bless $self, $class;
return $self;
}
sub call {
my ($self, $fn) = @_;
print $fn . " is called ";
}

my $obj = Test->new();
$obj->foo(a,b,c)
# will become $obj->call("foo", a, b, c);
$obj->bar(d,e,f);
# will become $obj->call("bar", d, e, f);

That's what AUTOLOAD is good for:

#!/usr/bin/perl

package XYZ;

use strict;
use warnings;

sub new {
my ( $class ) = @_;
my $self = { };
bless $self, $class;
return $self;
}

sub AUTOLOAD {
return if our $AUTOLOAD =~ /::DESTROY/;
print "$AUTOLOAD is called with ", join( ', ', @_), "\n";
}

1;

package main;

use strict;
use warnings;

my $x = XYZ->new( );
$x->foo( 3 );
$x->bar( 1, 2, 3 );

See for example

http://docstore.mik.ua/orelly/perl/prog3/ch10_02.htm
http://docstore.mik.ua/orelly/perl/prog3/ch12_05.htm

for more information.
Regards, Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top