On 12/04/2011 15:30, Shawn H Corey wrote:
On 11-04-12 10:15 AM, marcos rebelo wrote:
On Tue, Apr 12, 2011 at 15:54, Paul Johnson<p...@pjcj.net> wrote:
On Tue, Apr 12, 2011 at 03:26:49PM +0200, marcos rebelo wrote:
I have a code like:
foreach my $key ( ... ) {
my $sub = "get_$key";
$self->$sub;
...
}
If I can do this, I can also do it without the variable $sub.
You can do that. You can also do it without the variable $sub. But
please don't. It is much clearer with the variable in place.
What is the syntax? please
$self->${\"get_$key"};
But please pretend that the answer is "no, you need the variable
$sub".
This one is so ugly
What you're trying to do is called a symbolic reference. It is not
considered best practice. Instead, use a hash:
my %sub_hash = (
foo => \&foo,
bar => \&bar,
);
...
foreach my $key ( ... ){
$sub_hash{$key};
}
This would be fine if the subroutines weren't method calls. But to
support polymorphism, the /only way/ to make a reference is by name, and
the /only way/ to call a method by reference is using a scalar variable
holding the method name as a string.
This is proper and correct, because even if we could write
my $method_ref = \($object->method); # Incorrect code
we would be taking a snapshot of the method at that moment, but later on
there is no guarantee that $object->method will execute the same code.
However
my $method_ref = "method";
$object->$method_ref;
will always do the right thing.
Rob
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/