Wednesday, April 16, 2008

Fun with Perl....

Check out this gem Packy found today:

sub _app_run_args
{
my $runfile = shift;

my %server_args = do {
-r $runfile
or throw Error( "Un-readable version file: '$runfile'" );

-s _
or throw Error( "Empty version file: '$runfile'" );

# failing would be really wierd at at this point,
# but there is no telling...

open my $fh, '<', $runfile
or throw Error( "Failed open: '$runfile', $!" );

map
{
m{ ^\s* -(\w) \s* (\S+) \s+ }x
? ( $1 => $2 )
: ()
}
<$fh>
};

my %parms = ();

@parms{ qw( device log_path cfg_path app_dir dbname ) } =
@server_args{ qw( d e c M s ) };

return %parms;
}
If you're looking at this right now and thinking, "What the fuck?", well me too.

Let's look at some of the cute things here:

-s _
or throw Error( "Empty version file: '$runfile'" );

Nope, that underscore isn't a typo. Essentially this code says see if the previous file we were working on is greater than zero in size, and if not throw an error. But for readability's sake, why wouldn't you make that an if statement?

And how about this one:

map
{
m{ ^\s* -(\w) \s* (\S+) \s+ }x
? ( $1 => $2 )
: ()
}
<$fh>
Well, if you happened to know the file looked like the following, you could deduce that it's scanning over the contents of $fh and parsing out the arguments:

/sybase-stuff/sybase/ASE-12_5/bin/dataserver \
-d/sybase-stuff/sybase/master_device \
-e/sybase-stuff/sybase/ASE-12_5/install/SUNHAK.log \
-c/sybase-stuff/sybase/ASE-12_5/SUNHAK.cfg \
-M/sybase-stuff/sybase/ASE-12_5 \
-sSUNHAK \
Oh, and the results of the map are what is stored in %server_args, because that's the last statement in the block.