Category Archives: subroutines

Perl v5.20 combines multiple my() statements

Perl v5.20 continues to clean up and optimize its internals. Now perl optimizes a series of lexical variable declarations into a single list declaration. You can write them out as separate statements: my( $dog ); my( $cat ); my( $bird ); v5.20 turns that into a single declaration. my( $dog, $cat, $bird ); That doesn’t [...]

Perl 5.20 optimizes return at the end of a subroutine

Want to save 10 nanoseconds? Perl v5.20 optimizes a return at the end of a subroutine to use two fewer ops in the optimized version. During compilation, a subroutine like this one: sub some_sub { …; return $foo } turns into a subroutine like this one, without the return sub some_sub { …; $foo } [...]

Use __SUB__ to get a reference to the current subroutine

What if you want to write a recursive subroutine but you don’t know the name of the current subroutine? Since Perl is a dynamic language and code references are first class objects, you might not know the name of the code reference, if it even has a name. Perl 5.16 introduces __SUB__ as a special [...]

Make grep-like syntax

To create grep- or map-like syntax, you need to use Perl’s prototypes, despite whatever we told you in Understand why you probably don’t need prototypes. Perl needs the special hints that prototypes to parse a block as an argument to a subroutine. First, remember the forms of grep. There’s a single expression version and a [...]

Understand why you probably don’t need prototypes

You should understand how Perl’s prototypes work, not so you’ll use them but so you won’t be tempted to use them. Although prototypes can solve some problems, they don’t solve the problems most people want. Some languages, such as C, have function prototypes. You tell your function how many arguments it has and what sort [...]

Enchant closures for better debugging output

When you’re using code references heavily, you’re going to have a problem figuring out which one of them is having a problem. You define them in possibly several and far-flung parts of your program, but when it comes to using them, you don’t know which one you are using. You can’t really print its value [...]

Make your methods know as little as possible

How often have you wished that one of Perl’s modules did things slightly differently? That module mostly works for you except for some hard-coded decisions in string formats, pack specifications, or other minor point that you wish that you could configure. Or, maybe you’ve been the one to write that module. When you have to [...]

Eliminate needless loops and branching

On Stackoverflow, there’s the question How can I convert a number to its multiple form in Perl?. The best answer for the particular problem is Number::Bytes::Human. Beyond, that, many of the answers take the usual if-elsif-else, such as the one suggested by Michael Cramer: sub magnitudeformat { my $val = shift; my $expstr; my $exp [...]