in reply to Best way to match items in an array

Some suggestions:
use strict; use warnings; sub zip { my $file = shift; print "got a zip file $file\n"; } sub txt { my $file = shift; print "got a txt file $file\n"; } my @files = ("a.zip", "b.log", "c.zaaap", "d.txt"); #before you have a particular handler developed, #you can just set it to undef my %handlers = ("zip" => \&zip, "zaaap" => undef, "txt" => \&txt); my $pattern = join("|", map {"\\\.$_\$"} keys %handlers); print "pattern = $pattern\n"; foreach (grep {/$pattern$/} @files) { m/\.([^\.]*)$/; if (defined($handlers{$1})) { &{$handlers{$1}}($_); } else { print "No handler defined for $_\n"; } }

Replies are listed 'Best First'.
Re: Re: Best way to match items in an array
by ibanix (Hermit) on Dec 07, 2002 at 06:06 UTC
    That certainly is a unique way to do this, that I had not considered. However, what I expect that I will have many many different suffixes and it would be difficult to create a handle for each one.

    $ echo '$0 & $0 &' > foo; chmod a+x foo; foo;
      It is not required to have unique handler for each suffix. As the suffixes are just 'values' of the hash, not 'keys', so you can share handlers among suffixes. Also, you can make those handlers accept more parameters, for complex situation.
        Actually, I was thinking that I would have to code something like:

        my %handlers = ("zip" => \&zip, "zaaap" => undef, "txt" => \&txt, "ini +" => \&misc, "foo" => \&misc, ....);
        That is, if I have 50 different file types, do I need 50 different "end" => \&handler entries?

        In addition, my suffixes may not be known until the script is run...

        $ echo '$0 & $0 &' > foo; chmod a+x foo; foo;