Dave's Brain

Browse - Programming Tips - How can I compact/shrink perl code?

Date: 2011apr28
Updated: 2011aug4
Language: perl

Q.  How can I compact/shrink perl code?

A.  Here are some ways:

* Remove spaces

Before:

$hello = 'world';
After:
$hello='world';
* Remove newlines Before:
if ($condition) { doSomething(); }
After:
if ($condition) { doSomething(); }
Or:
if ($condition) { doSomething(); }
* Ident with tabs -- not spaces. * Remove semicolons. Did you know that (unlike in C) semicolons are separators not statement terminators. So every semicolon before a close brace bracket can be removed. Before:
if ($condition) { doSomething(); }
After:
if ($condition) { doSomething() }
* Invert "if" statements This removes the need for brace brackets if you are only doing one statement. Before:
if ($condition) { doSomething(); }
After:
doSomething() if ($condition);
* Remove quotes when using a hash Before:
$is_secure = $ENV{'HTTPS'};
After:
$is_secure = $ENV{HTTPS};
* Use "each" for readonly loops
http://www.google.com/search?q=perl+each
* Use "my" inside "for" Before:
my $i; for $i (1..10) { say $i; }
After:
for my $i (1..10) { say $i; }
* Use "map" and "grep"
http://www.google.com/search?q=perl+map http://www.google.com/search?q=perl+grep
* Use the negative pattern binding operator !~ Before:
if (!($string =~ m/target/)) { print "no match on target\n"; }
After:
if ($string !~ m/target/) { print "no match on target\n"; }
* There are many more ways. But try to keep your code readable too.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.