If someone malicious guesses the name of your subroutine, he can execute anything at will. That could be bad.
More likely, if there's a typo, it could call an undefined subroutine, which will have unexpected results. strict mode warns you about typos and other hazardous constructs to reduce these nasty surprises.
The oddly-named Re: use slack; presents one solution. Another would be to call UNIVERSAL::can() on an object, if you're using an object.
Otherwise, you might look through the package symbol table for a named glob, then check it for a code reference and call the code that way. It still requires disabling strict references, but it is a little safer and you can earn a Perl merit badge for knowing how:
Add the following to test:sub get_coderef { my $subname = shift; my $coderef; no strict 'refs'; $coderef = *{"$subname"}{CODE}; return $coderef if ($coderef and defined(&$coderef)); }
#!/usr/bin/perl -w use strict; sub do_this { print "doing this!\n" } sub do_that { print "doing that!\n" } my $code = get_coderef('do_this'); $code->(); $code = get_coderef('do_that'); $code->(); $code = get_coderef('do_nothing'); if (defined($code)) { $code->(); } else { print "Not defined!\n"; }
In reply to Re: How to use a scalar variable to call a subroutine?
by chromatic
in thread How to use a scalar variable to call a subroutine?
by apprentice
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |