my $vndr_key = (grep { $args->{desc} =~ m/$_/i } keys %vendors)[0];
if ($vndr_key ne '') {
#do something
} else {
#do something else
}
I'm getting an error Use of uninitialized value in string ne when the grep finds nothing.
I'm sure you already know what causes the warning. What others haven't stressed, is how you can simplify your code. You're really doing too much work.
my $vndr_key_count = grep { $args->{desc} =~ m/$_/i } keys %vendors;
if ($vndr_key_count) {
#do something
} else {
#do something else
}
grep() in scalar context returns the number of matches. With no matches, that is zero. And zero is false. There's no need to compare it to another false value, they needn't be the same anyway.
Hmm... what is it with you Perl newbies and that grep { $str =~ /$_/ } LIST thing? This will compile the regex for every loop. That will be rather slow. If you don't want pattern matches, don't use a regex, not like this: use index(). And if you do want it, this will be faster:
my $re = join '|', keys %vendors;
my $vndr_key_found = $args->{desc} =~ /$re/;
if($vndr_key_found) { ... } else { ... }
It's simpler. It's very likely a lot faster. |