CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
match part of a string in values of a hash

 



ssampath123
Novice

Nov 8, 2011, 11:56 AM

Post #1 of 3 (662 views)
match part of a string in values of a hash Can't Post

Hi Im stumped...:S.

I am trying to check if part of a certain string is located as a value in a hash.

this is an example of what I am doing right now.

Code
$val = "football"; 

if (grep { $_ eq /^.*$val.*/ } values %f1H ) {
print "Found\n";
}


I cannot rely on the hash key as I would like to explicitly search through the values of the hash. Also, note that since I only want to check if part of the string is located, I am using regex.

Say, one of the f1H hash values is:


Code
 
$f1H{10}="I like football very much";


Then the if statment should be true.

This does not seem work :S. Plz help!


wickedxter
User

Nov 8, 2011, 12:46 PM

Post #2 of 3 (659 views)
Re: [ssampath123] match part of a string in values of a hash [In reply to] Can't Post


Code
 
grep { print "Found " if $_ =~ /$val/ } values %f1H };


try that....


BillKSmith
Veteran

Nov 8, 2011, 7:15 PM

Post #3 of 3 (630 views)
Re: [ssampath123] match part of a string in values of a hash [In reply to] Can't Post

It appears that you want "Found" printed only once even if a match occurs in several values.


Code
 use strict;  
use warnings;
use List::MoreUtils qw( any );
my %f1H = (
key1 => 'I love basketball',
key2 => 'I love baseball',
key3 => 'I love football very much',
key4 => 'I watch Monday night footbal every week',
);

my $val = qr /football/;
if (any {$val} values %f1H) {
print "Found\n" ;
}



You can replace 'any' with 'scalar grep' if you do not want to use the module. I prefer 'any' because it documents your intention.



I see that you are using an integer (10) as a hash key. If all your keys are small integers, you probably should be using an array rather than a hash.
Good Luck,
Bill

(This post was edited by BillKSmith on Nov 8, 2011, 7:20 PM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives