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

Hi All
This is probably a very bad question but I still need to get my code correct

Could someone tell me how to fix this bad code
I'm not to sure how to 'NOT MATCH'


if($reference =~ m/38[0-9]{8}[A-Z]{3}/)<br> { } else { $reference = ""; }

Replies are listed 'Best First'.
Re: Regex 'If Not Match'
by Zaxo (Archbishop) on Sep 30, 2005 at 06:46 UTC

    The !~ binding returns true for non-matches,

    $reference = '' if $reference !~ m/38[0-9]{8}[A-Z]{3}/;
    or to keep the important part first and the match positive,
    $reference =~ m/38[0-9]{8}[A-Z]{3}/ or $reference = '';

    After Compline,
    Zaxo

Re: Regex 'If Not Match'
by strat (Canon) on Sep 30, 2005 at 07:10 UTC
    an alternative is unless which is the contrary to if
    unless ($reference =~ m/38[0-9]{8}[A-Z]{3}/) { $reference = ""; }

    If possible, I prefer unless way over !~ because I think it is better readable since I sometimes miss !~ at the first fast view to get the structure of a program

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

Re: Regex 'If Not Match'
by sh1tn (Priest) on Sep 30, 2005 at 06:46 UTC
    if($reference !~ m/38[0-9]{8}[A-Z]{3}/){ ... }
    You may want to read perlre.


Re: Regex 'If Not Match'
by Skeeve (Parson) on Sep 30, 2005 at 07:13 UTC
    The previouse answers are all correct.

    But have you really missed the obious way???
    if( not ( $reference =~ m/38[0-9]{8}[A-Z]{3}/ )) { $reference = ""; }
    And then there is also another way unless you don't like it, you may use:
    $reference = "" unless $reference =~ m/38[0-9]{8}[A-Z]{3}/;

    $\=~s;s*.*;q^|D9JYJ^^qq^\//\\\///^;ex;print
      Personally, I thought !~ was the obvious way. :)
Re: Regex 'If Not Match'
by halley (Prior) on Sep 30, 2005 at 23:40 UTC
    Last, but not least, let's say that you store your regular expressions in a config file or something. In many such situations, you can't change the application's logic to say "don't match this pattern." Yet, there's still a way, with negative lookahead assertions.
    my $re = qr/(?!\A.*38[0-9]{8}[A-Z]{3}.*\z)/; if ($reference =~ m/$re/) { # 38nnnnnnnnXXX pattern was not found $reference = ""; }

    --
    [ e d @ h a l l e y . c c ]