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

I would like to search an input file and match the regex error.*error on any line before doing anything else. If it does occur, then stop processing immediately. If it doesn't occur, then process the input file from the beginning normally. How might I do this? Thanks.

Replies are listed 'Best First'.
Re: match a word then exit
by almut (Canon) on Jul 14, 2008 at 15:18 UTC
    while (<>) { exit if /error.*error/; # do whatever you want to do... }

    (if you just want to exit the loop - not the program - use last in place of exit)

Re: match a word then exit
by massa (Hermit) on Jul 14, 2008 at 16:36 UTC
    I want the monks to do my homework to me...
    while( <> ) { exit 1 if /error.*error/ } open ARGV or die; while( <> ) { ... ## do your stuff }
    []s, HTH, Massa
Re: match a word then exit
by linuxer (Curate) on Jul 14, 2008 at 15:36 UTC
    #!/usr/bin/perl use strict; use warnings; # which file is to be checked my $file = shift @ARGV; die "no input file!\n" unless defined $file; # check with which regex my $regex = qr/error.*error/; # open file for reading open my $fh, '<', $file or die "$file: $!\n"; # try to match regex in file's content if ( ! grep { m/$regex/ } <$fh> ) { # nothing matched; rewind to file's beginning seek $fh, 0, 0 or die "can't reposition on filehandle!\n"; # process file linewise while ( my $line = <$fh> ) { # process file as desired print $line; } close $fh; } # regex matched; don't process file else { close $fh; die "error matched!\n"; } __END__
Re: match a word then exit
by Lawliet (Curate) on Jul 14, 2008 at 15:25 UTC

    open (FILE '<file.txt'); my @file = <FILE>; close FILE; foreach my $line (@file) { exit if $line =~ /error.*error/; # Process here }

    <(^.^-<) <(-^.^<) <(-^.^-)> (>^.^-)> (>-^.^)>
Re: match a word then exit
by ktl (Initiate) on Jul 14, 2008 at 21:51 UTC
    Thanks to all who took the time to reply to my post.