What have you tried? Did the obvious solution (i.e. map { $_ => $hash{$_} } grep { foo($hash{$_}) and bar($hash{$_}) } keys %hash) not work for you? Why not? Do you have any other ideas how this could be accomplished? Did you try them? What about them failed?
You should ask yourself these questions. Before you post. And then answer these questions in your post. I think you'll get more response this way.
| [reply] [d/l] |
Hello,
I am not that experienced with the Perl and I am not a programmer by nature although I have been touched by Perl since years, I still have no idea on how to use map,grep and bar inside hash tables. I can use it on arrays but that would be about it. I have tried to make it work the easy to understand way by using foreach loops and if statement and then pushing everything into a new hash but got totally stuck as you would be able to imagine. I could not find much documentation on the different handling possibilities of hash tables although I don't tend to use anything else then hash tables in my codes. If anybody has some good documentation/examples on how to use functions with hash tables like map and grep that would be great.
| [reply] |
I still have no idea on how to use map,grep ... inside hash tables
The basic technique in my example is fairly simple. First we filter out the hash keys we want, with grep. Once that list of wanted keys is obtained, we have to turn it back into a hash. This is what the map is for. The foo and bar were just examples. Those are your selection criteria (i.e. how you decide which keys you want to toss and which you want to keep).
Here it is laid out a bit more clearly. Remember, since the pipeline goes from right to left, read the comments from bottom to top:
my %newhash = # keys/values into a hash
map { $_ => $hash{$_} } # a list of keys/values
grep { foo($hash{$_}) # just the keys we want
and bar($hash{$_}) }
keys %hash; # a list of keys in %hash
Now, if there are a lot of keys in your hash (as you seem to imply), building all these big lists might be rather slow. I would try it before ruling it out, though. Also note that while we're making a whole new hash, the sub-hashes are not going to all get copied. The references will get copied, but they'll be referring to the same anonymous hashes as before. This shouldn't be a big bottleneck (but, again, without trying it's hard to say for sure).
I have tried to make it work the easy to understand way by using foreach loops and if statement and then pushing everything into a new hash but got totally stuck
This might be the way you want to go, if the map and grep solution is still too confusing. Again, if you show us the code you tried, we can try to help figure out why it's not working. You might want to post a new question, then reply here with a link to it. That way you get more people looking at it, but people following the discussion here can still follow the new post. | [reply] [d/l] [select] |