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

Esteemed Monks I humbly ask for your assistance,

In searching a flat text file I want to exclude certain rows from processing and copy these lines into my output file. I am successful when a line starts with a “2” as in this example:

if ( $line !~ m/^2/ ) {

I want to be able to do a similar thing when a group of 3 characters is found in positions 14-16, apply certain changes to line before writing it to the output file. My guess is that I would use an if ... then ... else statement and start the logic with something like this:

if ( $line, 14 !~ m/^801/ ) {

I would then define the processing parameters for this match and if no match then the row would be processed as usual.

Any help and advice would be appreciated.

Replies are listed 'Best First'.
Re: Ignoring lines in flat text file
by ikegami (Patriarch) on Sep 11, 2007 at 15:06 UTC
    if (length($line) >= 15 && substr($line, 14, 3) eq '801')

    or

    if ($line =~ /^.{14}801/)
      Thanks for the advice. I have changed my strategy to have the look up ignore the line as is as along as it does not match the 4 options listed in the code below but I get a syntax error. As I am still a newbie I am not sure what is wrong with this snippet of code:

      if ( $line !~ m/^2/ ) or ( substr($line, 14, 3) ne '800' ) or ( substr($line, 14, 3) ne '866' ) or ( substr($line, 14, 3) ne '877' ) or ( substr($line, 14, 3) ne '888' ) {


      Thanks again.

        The entire expression must be in parens.

        You also have logic errors. Your expression will always be true.

        if ( $line !~ m/^2/ || ( substr($line, 14, 3) ne '800' && substr($line, 14, 3) ne '866' && substr($line, 14, 3) ne '877' && substr($line, 14, 3) ne '888' ) ) { ... }

        That could be simplified using a regexp or a lookup table

        if ( $line !~ m/^2/ || substr($line, 14, 3) !~ /^(?:800|866|877|888)\z/ ) { ... }
        my %tollfree = map { $_ => 1 } 800, 866, 877, 888; if ( $line !~ m/^2/ || !$tollfree{ substr($line, 14, 3) } ) { ... }