Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   Help with test program (http://www.velocityreviews.com/forums/t900252-help-with-test-program.html)

joubertb@gmail.com 10-08-2006 08:47 PM

Help with test program
 
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 ?


Peter J. Holzer 10-08-2006 09:17 PM

Re: Help with test program
 
On 2006-10-08 20:47, joubertb@gmail.com <joubertb@gmail.com> wrote:
> 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


--
_ | Peter J. Holzer | > Wieso sollte man etwas erfinden was nicht
|_|_) | Sysadmin WSR | > ist?
| | | hjp@hjp.at | Was sonst wäre der Sinn des Erfindens?
__/ | http://www.hjp.at/ | -- P. Einstein u. V. Gringmuth in desd


All times are GMT. The time now is 04:13 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.