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.

In reply to Re: no grep match returns undefined? by bart
in thread no grep match returns undefined? by c

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.