Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

taking a slice of a hash

Status
Not open for further replies.

AMiSM

Technical User
Jan 26, 2006
128
US
Hi, all!
Is there something similar to the 'grep' function when working with hashes? e.g. -

%hash = ( "abc", "a"
"abd", "b"
"abe", "c"
"acd", "d"
"ace", "e" );

somefunction ( /ab/, %hash ); => ( a, b, c )
 
You can still use grep. Something like this will work:
Code:
my %hash = ( "abc", "a",
          "abd", "b",
          "abe", "c",
          "acd", "d",
          "ace", "e" );

my @results = map {$hash{$_}} grep {/ab/} keys %hash;
print "@results";
 
Yes. The function that is similar to grep for hash functions is .... wait for it .... grep!

That's right. grep is a more than one data type kind of function. It's very 21st century like that.

Just take advantage of the functions values and keys whenever wanting to perform grep operations on a hash.

The exact problem that you displayed above is rather simple unfortunately, but basically what I saw there was this.

# Give me all values of %hash where the key is similar to /ab/. Well if that's what you want, just code it out


%hash = ( "abc", "a"
"abd", "b"
"abe", "c"
"acd", "d"
"ace", "e" );

my @array = map {$hash{$_}} grep { /ab/ } keys %hash;


This returns. ('a', 'b', 'c') # Not necessarily in that order.
 
Well, I was overthinking the problem at hand, making it more difficult than it had to be. But this reply will be useful later, I'm sure!
Thank you both!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top