Hack 86. Optimize Away the Annoying Stuff


File off the rough edges of your code.

Sit down and look at the code you actually write every day. Is there something tedious that you do all the time, something that is a tiny (but constant) irritation? Maybe it's as simple as adding that final "\\n" to the end of just about every print command:

print "Showing first ", @results / 2, " of ", scalar @results, "\\n"; for (@results[ 0 .. @results / 2 - 1 ]) {     if (m/($IDENT): \\s* (.*?) \\s* $/x)     {         print "$1 -> ", normalize($2), "\\n";     }     else     {         print "Strange result: ", substr( $2, 0, 10 ), "\\n";     } }

The Hack

If you find that you have to tack a newline onto the end of most (or even just many) of your print statements, factor out that tiny annoyance:

sub say { print @_, "\\n" } # and ever after... say "Showing first ", @results / 2, " of ", scalar @results; for (@results[ 0 .. @results / 2 - 1 ]) {     if (m/($IDENT): \\s* (.*?) \\s* $/x)     {         say "$1 -> ", normalize($2);     }     else     {         say "Strange result: ", substr( $2, 0, 10 );     } }

Likewise, if you're forever opening a file and reading in the contents:

open my $fh, '<', $filename or die "Couldn't open 'filename'"; my $contents = do { local $/; <$fh> };

you could automate that:

sub slurp {     my ($file) = @_;     open my $fh, '<', $file or croak "Couldn't open '$file'";     local $/;     return <$fh>; } # and thereafter: my $contents = slurp $filename;

Hacking the Hack

The key here is to find the repetitive, low-level, mechanical things you do and hoist them out of your code into shorter, cleaner, higher-level abbreviations. Factoring out these common "micropatterns" makes the resulting code more readable and less prone to typos and other mishaps. It also frees you to concentrate on solving your actual problem.

There are already good implementations on CPAN for many of these micropatterns. For example, see Perl6::Say, File::Slurp, List::UtilTerm::ReadKey, or Sort::Maker. Subroutines like say( ) and slurp( ) are also prime candidates for adding to your standard toolkit [Hack #34].



Perl Hacks
Perl Hacks: Tips & Tools for Programming, Debugging, and Surviving
ISBN: 0596526741
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net