Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

$a="aaa"; $b=""; if($a=~/$b/){print "I found $b in $a\n";} else(print "I didn't find $b in $a\n";} If $a is somthing and $b is nothing I don't want to find nothing in something... How do I make it print "I didn't find $b in $a ....

Replies are listed 'Best First'.
Re: Don't want to match nothing
by Adam (Vicar) on Jul 06, 2000 at 03:48 UTC
    Then check that $b has a value. You could just use $b as the test, ie.
    if( $b and $a =~ /$b/ ) { do this }
    but I wouldn't do that in case $b == 0. I also wouldn't use eq in case $b is numeric or == in case $b is a string. So do something like,
    if ($b !~ /^$/ and $a =~ /$b/) { do this }
      Actually, ne should be fine, whether $b is numeric or not, and it's more efficient than a regex.

      if ($b ne '' and $a =~ /$b/) { do this }

      *Woof*

        You are right. I come from a C++ back ground, so I don't use ne or eq much, so I just figured that if you get the warning for == the you would get it in the reverse direction with eq. But since perl will happily convert a number to a string, the problem doesn't exist. For added fun I benchmarked the difference between the regex and ne:
        Y:\>perl -MBenchmark -we "print timethese( 10_000_000, {Regex, '$_=0; +print q[] if $_ !~ /^$/', NotEq, '$_=0; print q[] if $_ ne qq[]' } )" Benchmark: timing 10000000 iterations of NotEq, Regex... NotEq: 27 wallclock secs (26.41 usr + 0.00 sys = 26.41 CPU) @ 37 +8658.79/s (n=10000000) Regex: 37 wallclock secs (36.69 usr + 0.00 sys = 36.69 CPU) @ 27 +2531.55/s (n=10000000) HASH(0x8c134b0)
RE: Don't want to match nothing
by PipTigger (Hermit) on Jul 06, 2000 at 10:06 UTC
    Just do:
    if ($b ne "" && $a =~ /$b/) { print "found"; } else { print "not found"; }
    Werkie? TTFN.

    -PipTigger

    p.s. Initiate Nail Removal Immediately!