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

such a simple thing, from my tutorials there is nothing wrong with this code.
$input = "-lalala:lalala- hello"; #if "badinput" isnt in the string then print the string. if (!$input =~ m/badinput/) { print "$input!"; }
ripping my hair out :/

Replies are listed 'Best First'.
Re: totally lost
by JavaFan (Canon) on Apr 29, 2012 at 16:22 UTC
    Precedence. You're matching badinput against the negation of $input. Use:
    if ($input !~ /badinput/) { ... }
    instead.

    Or

    if (!($input =~ /badinput/)) { ... }
    but that's more typing, and less idiomatic.
Re: totally lost
by moritz (Cardinal) on Apr 29, 2012 at 16:33 UTC

    Another way to write it:

    unless ($input =~ /badinput/) { print $input; }

    Or even

    print $input unless $input =~ /badinput/;

    With perl 5.10 or newer you can also write

    use 5.010; given ($input) { print unless /badinput/; }

    Though usually it is a better idea to check for valid input (whitelisting) than checking for bad input (blacklisting).

      You do not need given, for/foreach is enough and works even in ancient perls.

      for ($input) { print unless /badinput/; }

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.