regex - string comparison for hash keys in perl -
i having hash map in perl this:
map_message_to_number => { 'hello world, xyz' => 11, 'i using stack overflow guidance' => 12, 'programming good!' => 13, },
in perl code trying make match hash key , if match happens return corresponding hash value ( number ).
my code working fine.
my $strtomatch = 'hello world, xyz!'; if ( condition ) { $val = map_message_to_number->{$strtomatch}; # code use return value dosomethingwith $val; }
my question here is: if see value of variable $strtomatch has 1 character '!' not present in original hash map. because of hash map not returns value.
my question how can make more generic can make comparison if part of strings match.
even few characters match fine return value.
let me know.
i not sure how can use regular expression here because doing comparison value in hash map value coming other function. technical , not programming, trying things learn.
here's 1 way it:
#!/usr/bin/env perl use strict; use warnings; %msg_to_number = ( 'hello world, xyz' => 11, 'i using stack overflow guidance' => 12, 'programming good!' => 13, ); $str_to_match = 'hello world, xyz!'; #note - grep returns list. chuck duplicate hits away. ( $first_match ) = grep { $str_to_match =~ m/\q$_\e/ } keys %msg_to_number; print "$first_match = $msg_to_number{$first_match}\n";
note - pattern match in grep reversed. check if string matches key in hash, , return if does. it'll work if key substring (or exact match) of primary string.
and gets 'first' match, practically speaking - if there duplicates, result random. make sure hash keys sufficiently unique.
e.g:
my $str_to_match = 'hello world, xyz!programming good!!!!!one'; ( $first_match ) = grep { $str_to_match =~ m/\q$_\e/ } keys %msg_to_number; print "$first_match = $msg_to_number{$first_match}\n";
will give randomly:
programming good! = 13 hello world, xyz = 11
as alternative - 1 possiblity perform common transform on input/output, makes 'blind' differences.
e.g.
#!/usr/bin/env perl use strict; use warnings; %msg_to_number = ( 'hello world, xyz' => 11, 'i using stack overflow guidance' => 12, 'programming good!' => 13, ); $str_to_match = 'hello world, xyz!!!!!'; $transformed_match = $str_to_match =~ s/\w//gr; ( $first_match ) = grep { s/\w//gr =~ m/^\q$transformed_match\e$/i } keys %msg_to_number; print "$first_match = $msg_to_number{$first_match}\n";
this strips \w
"not word" characters (like punctuation , whitespace) , compares 2 that. means matches bit fuzzier, , allow arbitrary exclamation marks, spacing etc.
if want handle default case, handy. //
operator want.
return $msg_to_number{$first_match} // "default value here " ;
(or can test defined on $first_match
)
for case insentive matching, i
modifier regex trick in second example.
Comments
Post a Comment