Help with test program

J

joubertb

I have been working on this for the past few days and still can't
figure out what I am doing wrong.

Below the my test program. Can someone point out to me what I am doing
wong?

Thanks.

--joubert

===========================< cut here >===============================

package foobar;

sub new {
my $class = shift;
my $self = {};

return bless $self, $class;
}

sub func {
my $self = shift;
my $param = shift;
print "inside function\n";

print "param=$param\n";

return "zzzzz";
}


$f = new foobar;

my %myarray = (
foo => { func => $f->func, }
);
#
# When I do the above assignment, it calls the method $f->func. What I
want it to do is assign the
# function pointer to func so that below I can call it.
#

#$myarray{foo}{func};
$xxx = $myarray{foo}{func}("abc123");
#
# When the function above is called, it says that "zzzzz" is does not
exist. It looks like the return
# value from $f->func is assigned to $myarray{foo}{func}.
#
# What am I doing wrong ?
 
P

Peter J. Holzer

I have been working on this for the past few days and still can't
figure out what I am doing wrong.
===========================< cut here >===============================

package foobar; [...]
sub func {
my $self = shift;
my $param = shift;
print "inside function\n";

print "param=$param\n";

return "zzzzz";
}


$f = new foobar;

my %myarray = (
foo => { func => $f->func, }
);
#
# When I do the above assignment, it calls the method $f->func.
Yes.

# What I
# want it to do is assign the
# function pointer to func so that below I can call it.
#

#$myarray{foo}{func};
$xxx = $myarray{foo}{func}("abc123");

If you want to call it like this (i.e., you don't want to call func on
any object, but always on $f), the best way is probably:

my %myarray = (
foo => { func => sub { $f->func(@_) }, }
);

if you want to be able to call func on arbitrary objects, I'd just store
the name and let perl find the right method at call time:

my %myarray = (
foo => { func => 'func', }
);

my $f2 = new foobar;
my $func = $myarray{foo}{func};
$xxx = $f2->$func("abc123");

There are other ways ...

hp
 

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

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top