in reply to Parse File With Sub While Loops

In the TIMTOWDI spirit, here is one that uses some sugar cooked up by thedamian.

Be forewarned, it makes some assumtions about your file format that may not be true.
#!/usr/bin/perl -w use strict; $|++; ## # NOTE: This code Assumes (and we all know what that means) that the +file # being fed to has no more than one "boundary" (/FH|BH/) per line, and + # that the file is delimited by newlines. # use Switch 'Perl6'; # Import thedamian's sugar, it's better than C&H. use English '-no_match_vars'; # since we're using some Perl 6 syntax h +ere, may # as well get rid of $0 in the usage sta +tement my $file = shift or die "USAGE $PROGRAM_NAME filename\n"; open( FH, $file ) or die "Coudln't open $file: $!\n"; my $batchnum = 0; # global batch tracker while (<FH>) { chomp(); next if m/^$/; given ($_) { when /^FH$/ { print "File Header\n"; last; } when /^BH$/ { print "Batch Header\n"; $batchnum++; last; } when /^FT$/ { print "File Trailer\n"; last; } when /.*/ { handle_batch_content($_); } } } sub handle_batch_content { my $batch_content = shift; print "Got $batch_content in $batchnum\n"; # or whatever else you wa +nt to do }
Given the example file you provided, assuming that Example is newline delimited, this script produces:
File Header
Batch Header
Got 1234123 in 1
Got 1234123 in 1
Batch Header
Got 1234963 in 2
Got 1234963 in 2
Got 1234963 in 2
Batch Header
Got 1234999 in 3
Got 1234999 in 3
Got 1234999 in 3
Got 1234999 in 3
Got 1234999 in 3
File Trailer
HTH,
  dug