For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > January 2006 > re: File Parsing Question









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author re: File Parsing Question
William Black

2006-01-22, 7:03 pm

Hello,

I'm trying to figure out how to read multiple lines from a file at once for
parsing. For example,, If the file contained the following:

input file
------------
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8

I want to read in lines 1-4 for processing then during the next iteration
read lines 5-8. Could someone give me a could starting place?




--
William Black
wjblack74@gmail.com

Shawn Corey

2006-01-22, 7:03 pm

William Black wrote:
> Hello,
>
> I'm trying to figure out how to read multiple lines from a file at once for
> parsing. For example,, If the file contained the following:
>
> input file
> ------------
> Line 1
> Line 2
> Line 3
> Line 4
> Line 5
> Line 6
> Line 7
> Line 8
>
> I want to read in lines 1-4 for processing then during the next iteration
> read lines 5-8. Could someone give me a could starting place?


I know of no other way than the hard way.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

while( ! eof DATA ){
my @lines = ();
for my $i ( 1 .. 4 ){
my $line = <DATA>;
push @lines, $line;
}

# process @lines
print Dumper \@lines;

}

__END__
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9


--

Just my 0.00000002 million dollars worth,
--- Shawn

"Probability is now one. Any problems that are left are your own."
SS Heart of Gold, _The Hitchhiker's Guide to the Galaxy_

* Perl tutorials at http://perlmonks.org/?node=Tutorials
* A searchable perldoc is available at http://perldoc.perl.org/
usenet@DavidFilmer.com

2006-01-22, 7:03 pm

William Black wrote:

> I want to read in lines 1-4 for processing then during the next iteration
> read lines 5-8. Could someone give me a could starting place?


You could use Tie::File which lets you treat the file just like an
array - then you just take 4-element slices of the array. In this
example, I use IO::All, which is simply a proxy for Tie::File (and a
bunch of other modules and functions); you can replace IO::All with
Tie::File if you prefer:

#!/usr/bin/perl
use strict; use warnings;
use IO::All;

my $data = io("/tmp/junk.txt");

print "First 4 lines are:\n",
map {"\t$_\n"} @$data[0..3];
print "Next 4 lines are:\n",
map {"\t$_\n"} @$data[4..7];

__END__

(you probably don't want to hardcode your array subscripts like that;
I'm just showing a quick-and-dirty usage illustration - adaptation to a
real program is left as an exercise for the reader.)

--
http://DavidFilmer.com

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com