Well, I left you neutral, but I suspect it's because one can use eval, and that doing what the poster is asking needn't be "deep magic" or responded to with what was essentially "you don't want to do that" without even a brief explanation of why.
For the record, eval could be used thus:
my $f = 'subroutine';
eval "$f";
sub subroutine {
print "In sub!\n";
}
You are right to say that there are many, many reasons why one doesn't want to use eval this way[0], and that there is probably a better solution. However, I would say that the OP simply didn't provide enough information about what (s)he is trying to accomplish for us to provide useful advice on what approach could prove safer and more efficient.
[0]: A few reasons, from the top of my head:
- Not strict-safe: the name of the func is a bareword string when eval'd
- Evaling a string without knowing what is in it is a security risk -- and if you know what's in it, a dispatch table or some similar structure is probably a better choice anyhow
- Evaling a string is slow (evaling a block isn't, compartively)
Yoda would agree with Perl design: there is no try{}
| [reply] [d/l] [select] |
would any of those who downvoted this care to explain why?
Perhaps it's the link to "perlre" which would seem to be completely useless for this task. Maybe you meant "perlref" instead.
--
< http://www.dave.org.uk>
"The first rule of Perl club is you do not talk about
Perl club." -- Chip Salzenberg
| [reply] |
D'Oh! Yet Another Typo(TM)... I'm updating it soon.
| [reply] |
I have not down-voted your node but I do think the knee-jerk anti-symref response in the case of symbolic CODE references is often inappropriate.
It is perfectly reasonable to use a Perl package as a dispatch table. After all that's excatly what Perl's object implementation does.
Do you think...
FOO->$bar();
...is really any better than...
no strict 'refs';
"FOO::$bar"->();
... when you are not thinking in a OO way?
It should be noted that the security concern often leveled at symbolic CODE refs (that a malicious user could use a qualified name to access a subroutine outside the dispatch table) actually applies in the indirect class method call but does not apply in the explicit symref case. | [reply] [d/l] [select] |
I take your point wrt CODE symrefs, and in fact I upvoted your post. OTOH in my experience I fully agree with the widespread consensus that symrefs in general are bad. Not to say that I do not use them myself when I do want to manipulate the symbol table, but that's a whole different story. In most standard situations in which newbies would (naively) like to use symrefs, real refs would only require a moderate amount of more typing, and if you're under strict, actually less, for you have to say no strict 'refs' then. So, all in all, they should be advised against doing so until they are knowledgeable enough to know when it would be the case.
| [reply] [d/l] |