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


I am parsing a rather large input file using the follow-
ing perl code:

while (my $line = <$fh>) { chomp($line); my ($uid, $login, $cpupr, $cpunpr, @data) = (split("\t",$line)); }


I want to stop parsing lines when a certain string is
found in the input file. Would anyone be able to
assist me in accomplishing this? I am able to use a
pattern match to determine when this string is found,
but I am not sure how to get perl to stop parsing lines
of input at this point. The pattern matching regular
expression is:

if ($line =~ /TOTAL COMMAND SUMMARY/)


I am putting this after 'split' line and before the
while loop ends.


I hope someone can tell me what to do in the block
associated with this if statement or maybe this should
be some other kind of control loop.

Replies are listed 'Best First'.
Re: Terminating Read Of Input
by moritz (Cardinal) on Aug 14, 2007 at 13:33 UTC
    See last

    while (my $line = <$fh>) { chomp($line); last if ($line =~ /TOTAL COMMAND SUMMARY/); my ($uid, $login, $cpupr, $cpunpr, @data) = (split("\t",$line)); }

    (Update: execute last prior to split.)

      And to make your intention slightly more obvious you can label the loop:

      READ_TILL_TOTAL: while (my $line = <$fh>) { chomp($line); last READ_TILL_TOTAL if ($line =~ /TOTAL COMMAND SUMMARY/); my ($uid, $login, $cpupr, $cpunpr, @data) = (split("\t",$line)); }

      This is especially helpful if you've got other loops around this block, for example a loop that opens a list of files and reads them all in turn.


      All dogma is stupid.
      Since this is a while loop, why not just put the check in the while condition?
      while( my $line = <$fh> and $line !~ /TOTAL COMMAND SUMMARY/) { ... }
Re: Terminating Read Of Input
by perlofwisdom (Pilgrim) on Aug 14, 2007 at 17:45 UTC
    Try this... for my $line (<$fh>) { last if ($line =~ /TOTAL COMMAND SUMMARY/); chomp($line); my ($uid, $login, $cpupr, $cpunpr, @data) = (split("\t",$line)); }