Is Perl Best Practice recommended to have a method name in a string?

Is the following code available in Perl Best Practice?

my $method_name = q{someMethod}; $self->$method_name(); 

I know this is a suspicious style, but does PBP have anything to say about it?

+5
source share
1 answer

The Perl :: Critic module on CPAN has a utility called perlcritic , the purpose of which is to identify any violations of Perl Best Practices recommendations. However, this is not limited to PBP, and there are many policy modules in CPAN that connect to Perl :: Critic to provide additional rules. If you prefer not to install Perl :: Critic, you can paste your code into perlcritic.com and get feedback at any of the standard Perl crit levels, carelessly and cruelly.

Consider the following script:

 package Foo; use strict; use warnings; sub new { bless {}, shift; } sub bar { print "Hello\n"; } package main; use strict; use warnings; my $f = Foo->new; my $method = 'bar'; $f->$method(); 

When I run perlcritic myexample.pl --brutal , I get no complaints about the facilities used to invoke the method.

I read Perl Best Practices and again searched to mention symbolic method calls and found nothing. This does not mean that I did not miss references to such constructions, but I cannot find them. And Perl :: Critic's built-in policies supporting PBP seem to agree.

There are actually examples of such in the book Damian Conway , Object Oriented Perl . Of course, Damian wrote PBP many years after the OOP, and both are old enough that in many cases the best practices have emerged.

But still it's great to think about what the most convenient coding styles might be. And if you are concerned that the construction of $object->$method() may be difficult to maintain, be sure to avoid it unless you have a great reason not to. And in these cases, isolate the use of the narrowest parts of well-documented code.

Perhaps a cleaner practice is to get a reference to this method, not a symbol. This can be done using can :

 my $method = $f->can('bar'); $f->$method(); 

The call tool looks something like this, but the $ method contains a link to the code, which is probably less error prone. First, can will throw an exception when it is thrown if there is no bar , and not an exception that occurs when the actual method is called. This is a more secure programming approach. And using can instead of just referring to this method, as in my $method = \&Foo::bar has the advantage of playing nice with inheritance, which is not in the wired link.

+13
source

All Articles