Whenever there is talk of symbolic references, someone has to point out at least the following three sources for why they should not be used :
And, to this i would like to add this node, from tye about a limitation of symbolic references, if you do use them.
from the frivolous to the serious | [reply] |
Can this indeed be done?
Yes, it can be done, using symbolic references. But, symbolic references (using a string to determine the variable name of a global) is considered very bad and very unmaintainable. You are right about using hashes: they're a lot better than having variable variable names.
$object->$name_of_method() is perfectly valid, but the syntax for the symbolic reference would be ${ $_ } or $$_ (I'd even use ${ "$_" } to make sure no-one will think $_ holds a real reference). Please don't use symbolic references (fortunately, strict doesn't allow you to) and use a hash instead.
U28geW91IGNhbiBhbGwgcm90MTMgY
W5kIHBhY2soKS4gQnV0IGRvIHlvdS
ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
geW91IHNlZSBpdD8gIC0tIEp1ZXJk
| [reply] |
It can be done, very easily, but it can lead to problems.
sub test {
print "nothing\n";
}
my $var = 'test';
&$var;
# will call the sub, if you are not using strict.
This code will issue a run-time error if you are using strict.
However, if you do the same thing with objects, even with
use strict, you can get away with it.
(This is one of the cases where Perl gives you splendid
opportunities of shooting yourself in the foot.)
#!/usr/bin/perl -w
use strict;
package Camel;
sub new {
my $class = shift;
my $self = bless {name =>'Jack Camel'}, $class;
}
sub who {
my $self = shift;
return $self->{name}
}
sub what {
my $self = shift;
return "a camel, can't you see that?";
}
package main;
my $camel = new Camel;
for ('who', 'what') {
print $_, "?\t", $camel->$_, "\n";
}
But you will be in trouble if you add an unmatched item to
the list of variables, or you misspell one of them.
Say, using ('what','woh'),
the error will kick off at run-time only.
I very much agree with Juerd's advice.
Don't do it.
| [reply] [d/l] [select] |
True, but you won't get a compile-time error for non-existant method calls no matter how you call the bogus method. i.e.
package main;
my $camel = new Camel;
print "Who", "?\t", $camel->woh, "\n";
Compiles just fine... if you're gonna mistype the name of a method it doesn't matter whether the method name is symbolic or hard-coded (thought the typo on a symbolic reference may be far from the method call and harder to find.)
Gary Blackburn
Trained Killer | [reply] [d/l] |
| [reply] |