Reputation: 61
I have a Perl program code that pulls a description string from a hash.
I have my variable $ui
equal to the variable $uniqueID
, but what I want is to return true if $ui
contains any words in variable $unqiueID
. But =~
isn't working.
Is there a smart way of doing this?
sub getDescription {
my $uniqueID = shift;
my $retval;
my $ui;
foreach my $key ( keys %HASHLIST ) {
foreach $ui ( @{ $HASHLIST{$key}->{uniqueID} }) {
if ( $ui eq $uniqueID ) {
$retval = $HASHLIST{$key}->{description};
last;
}
}
last if $retval;
}
return $retval;
}
Upvotes: 0
Views: 67
Reputation: 126722
Your purpose isn't clear, but it sounds like $uniqueID
is a list of words, and you want the first entry in %HASHLIST
whose uniqueID
matches any one of those words
This will do that for you, but I must say that your data structure isn't ideally suited to this job
sub getDescription {
my ($uniqueID) = @_;
my %wanted = map { $_ => 1 } split ' ', $uniqueID;
for my $ui ( values %HASHLIST ) {
my @ids = @{ $item->{uniqueID} };
return $item->{description} if @wanted{@ids};
}
return $retval;
}
Upvotes: 0
Reputation: 8901
A simple way to test if one scalar variable contains another is:
if ($ui =~ /$uniqueID/) {
...
}
(And as @Markus Laire points out you can also use /\b$uniqueID\b/
to prevent partial word matches.)
Upvotes: 2