in reply to Best way to match items in an array
I hope I understood your question
# This is untested code! my @dlcopy = @dir_list ; my @extensions = qw(zip log whatever) ; my %matches ; foreach my $ext (@extensions) { my @nonmathing ; my @matching ; foreach my $file (@dlcopy) { if ($file =~ /\.$ext$/) { push @matching,$file ; } else { push @nonmatching,$file ; } } @dlcopy = @nonmatching ; $matches{$ext} = \@matching ; }
That is: you work on a copy of @dir_list, iterating on it; you save in @nonmatching just the files that didn't match the pattern, and in @matching those that match. At the end of every cycle you shorten the inner foreach, since you are working only on those files that didn't match before. At the end of the game %matches contains all @dir_list elements that matched, and @dl_copy all those that didn't
Of course, we can heavily optimize this; the double foreach could be optimized, for example using ?:, array references and only one push instead of the if block. And, of course, the pattern matching could be "half-hardcoded" with an eval at each cycle...
But, at least, this should be clear code, even if untested :-)
Ciao!
--bronto
# Another Perl edition of a song:
# The End, by The Beatles
END {
$you->take($love) eq $you->make($love) ;
}
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Best way to match items in an array
by bronto (Priest) on Dec 07, 2002 at 14:03 UTC | |
|
Re: Re: Best way to match items in an array
by bronto (Priest) on Dec 07, 2002 at 14:17 UTC |