I am reading Code Complete 2, and one of the points mentioned is about creating subroutines even for operations that seem too simple to have their own subroutines, and how that can be helpful.
I know I can inline functions in C and C++ using the inline
keyword. But I never came across a way to inline subroutines in Perl.
Is there a way to tell the Perl interpreter to inline the subroutine calls (or why not)?
Best Answer
Constant subroutines, i.e. subroutines with an empty prototype and constant return value, are inline. That is how the constant pragma defines constants:
would be inlined if it is seen before its first use.
Otherwise, Perl allows subroutines to be dynamically redefined at run time, so inlining is not suitable.
For subroutines that always return the same value given the same inputs, you can use memoization.
Chapter 13 of Programming Perl provides some information on the optimization steps taken by
perl
.See also perldoc perlguts.
You can see the effect of constant-folding yourself:
Output:
Here, constant folding led to the replacement of the
if
block with ado
block because the compiler knew thatlog_ok
would always return a true value. On the other hand, with:Deparse output:
A
C
compiler might have replaced theif (log_ok)
withif ( 0.5 > rand )
.perl
does not do that.