perl - How can I quickly filter a hash given an array of keys? -



perl - How can I quickly filter a hash given an array of keys? -

this over-engineered solution think can done better. takes array of keys create filter string, checked against every key in hash see if key has index in filter string... exclude flag flips logic include or exclude based on result of _filter. not best way. improve ways?

sub _filter{ ($filter,$key,$joiner) = @_; $joiner = $joiner ? $joiner : '+'; $i = index($filter,$key); if($i >= 0){ $c; $c = substr($filter, $i-1, 1); print stderr "\nc => $c [$key][$i]"; if($i==0){ homecoming 1; } return($c eq $joiner); } homecoming 0; } sub hashfilter{ my($hash,$filter_keys,$exclude) = @_; homecoming 0 unless ishash($hash) && $filter_keys; $exclude = $exclude ? $exclude : 0; $filter = isarray($filter_keys)? join('+',@$filter_keys) : $filter_keys; print stderr "filter > $filter"; $p = {map { ( _filter($filter,$_) == $exclude ) ? ($_ => $$hash{$_}) : () } keys %$hash}; homecoming $p; } #isarray() , ishash() check ref value "array" or "hash" respectively

...using standard perl without additional modules! =]

some thoughts here?

using map, , index... these fast-ish methods vs doing regex, or there improve functions use?

hash slice, anyone? :

my %filtered_hash; @filtered_keys = grep { exists $hash{$_} } @filtered_keys; @filtered_hash{@filtered_keys} = @hash{@filtered_keys};

arrays perl hash filter

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -