Wednesday, January 14, 2009

Perl promotes laziness

#
# We need to open a set of files for writing, and reference the paths later;
# the hash gives us a nice way to work with them later.
#
my %lgfiles = ( pidfile     => "${datadir}/${0}.pid",
                errlog      => "${datadir}/${0}.err"
                ...         => ... );

# but how do we open the set of files?


# this is a lot of typing, but common style in some places
open PIDFILE,   ">", $lgfiles{pidfile}     or die "some message: $!";
open ERRLOG,    ">", $lgfiles{errlog}      or die "some message: $!";
open ...,       ">", $lgfiles{...}         or die "some message: $!";


# this is better, but still too much typing
{
    my $msg = 'some message:';
    open PIDFILE,   ">", $lgfiles{pidfile}     or die "$msg $!";
    open ERRLOG,    ">", $lgfiles{errlog}      or die "$msg $!";
    open ...,       ">", $lgfiles{...}         or die "$msg $!";
}


# this is handy
#
# open each key in %lgfiles for writing to as KEY
#
while (my ($k, $v) = each %lgfiles) {
    open uc($k), '>', $v or die "can't open $v: $!";
} 

# same thing, but faster to read (IMHO)
#
# open each key in %lgfiles for writing to as KEY
#
map { 
       my $fn = $lgfiles{$_};
       open uc($_), '>', $fn or die "can't open $fn: $!";
    } keys %lgfiles;



For some reason, the intregration of regular expressions, qw/quote words/, map {} @list, grep {} @list, the $_ default variable, and the do_something or die $! thing are my favorite features of Perl. While in most other languages, the only great feature I get to enjoy is the trinary/ternary ?: operator, when there's a place that it improves readiblity and reduces visual clutter ;-).


Ok, so my biggest beefs about Python 2.5 is no ? : and having to import re, hehe

No comments:

Post a Comment