in reply to Expand your world

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.

Replies are listed 'Best First'.
RE: RE (tilly) 1: Expand your world
by jlp (Friar) on Aug 20, 2000 at 11:13 UTC
    I have trouble with your assertion that this will be more efficient. Any gain in perfomance by using a hash instead of an if-else clause is going to be offset by the multiple eval()s. I also contend that it is just as easy to add another elsif as to add another key-value pair to the hash. Anyway, that's just my opinion.
      If you have a long list of arguments, it will be.

      First of all evals don't cost much more than just having had that much code in the first place. Secondly all of the evals take place up front. So it is just like having a longer program.

      But at runtime I have a hash lookup (constant time no matter how large the hash is) rather than repeated tests, So I have traded compile time away for faster run-time behaviour.

      FWIW I first realized the importance of this win when trying to speed up a program that categorized states into ACLI regions for a huge amount of text information. Just moving the logic out of if/elsif/elsif/else type constructs into hash lookups and/or smart REs was an order of magnitude improvement.

      Cheers, Ben