http://www.perlmonks.org?node_id=229044

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

I often use =~ to see if a string contains a value such as $string=~"hello" but how do I see if a string does not contain a value? For example say if a string does not contain "hello" do this?

Replies are listed 'Best First'.
Re: string does not contain
by pfaut (Priest) on Jan 22, 2003 at 15:34 UTC

    You can use !~ instead of =~. So, $string !~ "hello" would return true if the string doesn't contain "hello". See perlop (perldoc perlop) for more information on operators.

    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: string does not contain
by broquaint (Abbot) on Jan 22, 2003 at 15:37 UTC
    Just use the negated version of the regex match operator !~ e.g
    my $string = "foo bar baz"; print "no hello" if $string !~ /hello/; __output__ no hello
    See. perlop for more info.
    HTH

    _________
    broquaint

Re: string does not contain
by aging acolyte (Pilgrim) on Jan 22, 2003 at 15:41 UTC
    TMTOWTDI

    negate the if to an unless:

    my $string = "foo bar baz"; print "no hello" unless $string =~ /hello/;
    A.A.
Re: string does not contain
by fredopalus (Friar) on Jan 22, 2003 at 15:46 UTC
    You may also want to look at perldoc perlretut. It explains the two operators (=~ and !~) right in the beginning.
Re: string does not contain
by Hofmator (Curate) on Jan 23, 2003 at 13:07 UTC
    ... and as nobody mentioned it so far, if you just match against a literal string like 'hello', then you could also use the index function:
    # if 'hello' not contained in $string if ( index($string, 'hello' ) == -1) { # do something }

    -- Hofmator

Re: string does not contain
by OM_Zen (Scribe) on Jan 22, 2003 at 17:29 UTC
    Hi ,

    $string !=~ /hello/ or unless($string =~ /hello/)


    or that implies if not or a negate logic shall work for the not parsing a string value
      Close.   Actually, $string !~ /hello/   or ! ( $string =~ /hello/ )
        p