
alphabetical subset of hash keys
: If I have a large hash, how can I run a routine on just the keys that
: start with a certain letter?
[snip]
: foreach $key (keys %myhash) {
: if ( substr($key,0,1)=="A" ) { print "$myhash{$key}\n" };
: }
:
: but without having to bang through every key in the hash to see if it
: starts with 'A' (that just seems inefficient to me)
In terms of efficiency, unpack is probably a better choice than substr,
e.g.
foreach $key (keys %hash) {
## use the eq (not ==) operator for string comparison
## VV
next unless unpack("A", $key) eq "A";
...;
}
Still, this is a microoptimization, and not likely to produce huge
savings (unless you're dealing with very large hashes in terms of the
number of keys). Greater efficiency will probably come from a change
in your general approach to your data (read: algorithm).
: BTW - this hash is tied to a BTREE Berkely DB, so the hash keys will
: be returned in alphabetical order. What I'm trying to do is allow the
: user to 'query' the database by letter.
I don't know what you're using these data for, but would it help to
organize your data into separate hashes (say, a hash for each letter
of the alphabet)?
: John L Capell (remove "SpamMeNot" from reply-to eMail)
To receive email replies, put a replyable address in your Reply-To:
header. :-)
Hope this helps,
Greg
--
open(G,"|gzip -dc");$_=<<EOF;s/[0-9a-f]+/print G pack("h*",$&)/eg
f1b88000b620f22320303fa2d2e21584ccbcf29c84d2258084
d2ac158c84c4ece4d22d1000118a8d5491000000
EOF