[Chicago-talk] Delete element from array
Andy_Bach at wiwb.uscourts.gov
Andy_Bach at wiwb.uscourts.gov
Fri Jul 11 12:44:51 PDT 2008
Another cute trick - use a hash for your bad (or good, which ever is easist
to know ahead of time) symbols:
use warnings;
use strict;
my @symbols = qw(foo fiv fib fink fort futz);
my %bad_symbols = (
foo => 1,
fort => 1,
);
print "Sym: ", join(", ", @symbols), "\n";
@symbols = grep { not $bad_symbols{$_} } @symbols;
print "Sym: ", join(", ", @symbols), "\n";
In a process like this:
sub symbol_is_bad {
my $symbol = shift;
if (foo1) {
return 1;
}
if (foo2) {
return 1;
}
...
return;
}
my @good_sym = grep { not symbol_is_bad($_) } @sym;
depending upon the size and repetiveness of the data and dynamicn-ness and
cost of the tests, the sub is good candidate for 'memoization'. There's a
CPAN module for this, but basically it's a matter of avoiding the retest by
caching the results (in a hash say):
my %bad_symbols;
sub symbol_is_bad {
my ($test_sym) = @_;
return 1 if $bad_symbols{$test_sym};
my $symbol = shift;
if (foo1) {
$bad_symbols{$test_symj}++;
return 1;
}
if (foo2) {
$bad_symbols{$test_symj}++;
return 1;
}
...
return;
}
]my @good_sym = grep { not symbol_is_bad($_) } @sym;
Following PBP, you might want to refactor there to remove the various
returns (and set a specific return value for failure) inside the "if" tests
- set a flag and handle it at the end, using elsif to make it case stmt but
....
a
-------------------
Andy Bach
Systems Mangler
Internet: andy_bach at wiwb.uscourts.gov
Voice: (608) 261-5738 Fax: 264-5932
Accordion, n.: A bagpipe with pleats.
More information about the Chicago-talk
mailing list