Hashes are more efficient to execute than this kind of
explicit logic. Consider this untested code:
#!/usr/bin/perl -w
use strict;
use vars qw( $cmd_match %decomp_cmd %decomp_handler );
(scalar @ARGV) || die "Usage: $0 file(s)\n";
%decomp_cmd = (
'.tar.gz' => 'tar -zxvf $_',
'.tgz' => 'tar -zxvf $_',
'.bz2' => 'tar -Ixvf $_',
'.z' => 'uncompress -dc $_| tar -xvf -',
'.zip' => 'unzip $_',
);
# Set up subs
foreach (keys %decomp_cmd) {
$decomp_handler{$_} = eval qq(
sub {
if (system "$decomp_cmd{$_}") {
die("Cannot run '$decomp_cmd{$_}': $! (ret $?)\n");
}
}
);
}
# Set up match
{
my $str = join "|", map {quotemeta($_)} keys %decomp_cmd;
$cmd_match = qr/$str/;
}
foreach (@ARGV) {
if (/($cmd_match)$/) {
$decomp_handler{$1}->();
}
else {
warn("Don't know what to do with $_\n");
}
}
Definitely overkill here. But you see the concept. It will
perform quite well, is easy to extend, and moves all of the
logic you should ever want to change into one place. |