Perl Idiom

KirrilyRobert's favourite Perl idioms:

 $filename = param('filename') || "default";
 $filename ||= "default";

my @a = qw(foo bar baz);

print qq(<a href="stuff">with quotes</a>);

s{/usr/bin}{/usr/local/bin};

my %named_params = @_;

The Englishy stuff:
 return unless $condition;
 s/a/b/ foreach @element;
 s/a/b/, s/foo/bar/ for $onevar, othervar;   # multiple subs to multiple vars
 open(F, "file") or die "Couldn't open 'file': $!";
 if ($conditionA or not $conditionB) ...

Others: EnPassant

...

KarlKnechtel's quick table lookup PerlIdiom:

 $result = ['foo', 'bar', 'baz']->[$selector];

MarkJasonDominus's favorite PerlIdiom:

 use Fcntl ':flock';
 flock *DATA, LOCK_EX|LOCK_NB or exit;

(When you want to be sure that at most one instance of a program is running at any time. The obvious solution: Have the program try to lock a file when it starts up; if the file is already locked, the process should exit. But what file? Idiomatic solution: Have the program lock the file that contains its own source code!)


CategoryIdiom


EditText of this page (last edited December 16, 2003) or FindPage with title or text search