[Maine-pm] calling callbacks as object methods via hash lookup

maine-pm at mail.pm.org maine-pm at mail.pm.org
Fri Jul 9 08:59:51 CDT 2004


Hello out there,

I was wondering if anyone has a better mousetrap for doing a hash 
lookup, a subroutine dereference and a method call all in the same 
statement. It looks easy in two statements, but the only way I can 
figure out to do it in one statement is with an extra 
reference/dereference:

++++++++++++++++++++++++++++++++++

#!/usr/bin/perl

# callback_hash_test.pl
# Purpose: test calling callbacks as object methods via hash lookup.
# Use: command line

use strict;
package MyClass;

sub new {
	my $self = {
		'process' => \&my_process
	};
	bless $self;
	return $self;
}

sub my_process {
	my ($self, $word) = @_;
	return "Your word is $word";
}

package main;

my $object = MyClass->new();
print $object->{'process'}, "\n";

# THE TWO-LINE METHOD
my $process = $object->{'process'};
my $string = $object->$process("my_word");

print $string, "\n";

++++++++++++++++++++++++++++++++++

This prints, as expected...

CODE(0x8105d8)
Your word is my_word

The only way that I can figure out to do it in one statement is to 
reference and immediately dereference the code ref. This works:

++++++++++++++++++++++++++++++++++

my $string = $object->${\$object->{'process'}}("my_word");

++++++++++++++++++++++++++++++++++

Is there a way to do this without the intervening reference/dereference?

I suppose I could call it as a regular subroutine and pass the object 
as the first argument, but then it wouldn't be dispatched like a method 
should be, inheritance-wise.

Here are some of my attempts and the resulting error messages. The 
first one seemed the most promising, but since the object is based on a 
hash I believe the statement was interpreted as a hash lookup.

# my $string = $object->{$object->{'process'}}("my_word");
# Can't use string ("") as a subroutine ref while "strict refs" in use
# I suppose $object->{'process'} is being stringified for what looks 
like a hash lookup.

# my $string = $object->($object->{'process'})("my_word");
# Not a CODE reference

# my $string = $object->$object->{'process'}("my_word");
# Can't locate object method "MyClass=HASH(0x801294)" via package 
"MyClass"

# my $string = $object->&{$object->{'process'}}("my_word");
# syntax error ... near "->&"

# my $string = $object->${$object->{'process'}}("my_word");
# Not a SCALAR reference

# my $string = $object->{&$object->{'process'}}("my_word");
# Not a CODE reference

Thanks,

Bogart




More information about the Maine-pm mailing list