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

I want to check for the ocurrance of a particular two letter code in a line of text. If the line of text contains leading whitespace, that line must not be processed. How can this be done? Please advise. Thanks, ICG

Replies are listed 'Best First'.
Re: Negating a leading whitespace
by Limbic~Region (Chancellor) on Jul 05, 2005 at 15:16 UTC
    icg,
    If I understand correctly, you want to do something with a line if it contains 2 characters but exclude it if they are preceded by a whitespace. Negated character classes to the rescue:
    if ( $line =~ /[^\s]XY/ ) { ... }
    Where XY are the two characters you want. Alternatively, if the whitespace requirement for exclusion is at the beginning of the line you can just do:
    while ( <FILE> ) { next if /^\s/; # process lines without leading whitespace here ... }

    Cheers - L~R

      Your first example wouldn't match a line that began with XY, because it requires some character to precede it. Negative lookbehind or an alternation would fix:
      /(?:^|\S)XY/ # or /(?<!\s)XY/
      (I also prefer the builtin not-whitespace char, rather than negating the class).

      Caution: Contents may have been coded under pressure.
      I believe OP wants to check for the 2 chars _anywhere_ in the string, as long as the line doesn't start w/whitespace (so your second method)... I think this is easiest w/just two checks (i was having trouble making a single regex w/look-behinds):
      if ( $line =~ /^\S/ && $line =~ /XY/ ){ ... }
      Unless you can assume that the 2 chars will never be at the beginning of the line, in which case you can just do:
      if ( $line =~ /^\S.*?XY/ ){ ... }
Re: Negating a leading whitespace
by Anonymous Monk on Jul 05, 2005 at 15:53 UTC
    Assume you are looking for "AB", then use:
    /^(?!\s).*AB/
    or if you can use two regexes:
    !/^\s/ && /AB/
    the latter is likely to be faster.
Re: Negating a leading whitespace
by dirac (Beadle) on Jul 05, 2005 at 15:44 UTC
    #!/usr/bin/perl -w
    use strict;
    
    my $test = "some random text with char X and char Y that I want ... X and Y Y ...\n";
    my $occurs = ($test =~ tr/XY//);
    print "Your letters occurs ",$occurs," times\n";