Le Mer 19 Mai 2010 16:24:10, jeff@imaginative-software.com a écrit :
Show quoted text> That's an interesting pattern. Why wouldn't you use the constant or
> Readonly pragmas for those? Do you override those subs (in
> subclasses, for example)?
The Perl compiler knows how to /inline/ subs which are composed of just
one value to return, *and which have a '()' prototype* (I missed this
last part in the description of the issue).
So the real issue is for:
sub MY_INTEGER () { 1 }
sub MY_STRING () { "Hello" }
So this is a good way to create constants that are portable without
requiring 'constant' or 'ReadOnly', and this is also faster at runtime.
Try this:
perl -MO=Deparse -e 'sub HELLO () { "Hello\n" } print HELLO;'
See "Constant functions" in perlsub:
http://perldoc.perl.org/perlsub.html#Constant-Functions
Show quoted text> Detecting a sub that contains only a literal string or number is
> fairly easy. But in the general case, detecting a constant
> expression is not trivial...
>
> sub foo { oct( 1 + 7 ) . "bar" }
Perl knows tries to inline if the prototype is ()
sub foo() { oct( 1 + 7 ) . "bar" }
The general case is the one that Perl 5 knows how to inline.
perl -MO=Deparse -e 'sub foo () { oct( 1 + 7 ) . "bar" } print foo;'
Show quoted text> That may be nonsensical, but technically, it is a constant expression.
> So I think what you probably want is something more specific. I
> could imagine a Policy to enforce that all subs named in ALL_CAPS
> must not have returns, but that is a slightly different rule.
I agree this would be a different, and this is not my issue.
Show quoted text> In any case, I doubt we would ever add this to the Perl::Critic core.
> I think Conway would feel the merits of consistency (i.e. always
> use "return") are more important than the convenience of not using
> "return" in a small set of cases. But you could certainly release
> your own variant of RequireFinalReturns as a plugin :]
>
> But if you think I'm wrong, you're welcome to try and persuade me.
I hope so, now that I've made the exception rule stricter. ;)
I just want an exception to the rule for a common Perl idiom which makes
programs readable but still portable with old Perl which do not have the
'constant' module.
Also the point of the RequireFinalReturn rule is to make code more
readable. But the case of a single constant expression is already
readable and adding "return" only adds verbosity.
So, fixing the simple case of a one-term sub would be a step in the good
direction.
--
Olivier Mengué -
http://o.mengue.free.fr/