Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Parse File With Sub While Loops

by dug (Chaplain)
on Sep 16, 2002 at 23:03 UTC ( [id://198395]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://198395]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (3)
As of 2024-04-26 01:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found