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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|