Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-20 05:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found