Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to read consective lines from a file

Status
Not open for further replies.

bc819

Programmer
Jan 27, 2006
9
US
I'd like to read several consective lines from a file. Could someone show me how to do it. I know i can put several foreach loops, but it is very clumsy. Thanks.

Here what i did:
open (FILE, "t") || die "can't open t.num: $!";
# create an array of the the file content
@input = <FILE>;
# close the file to save memory
close (FILE) || die "can't open t.hex: $!";

# set your stop line
$stop1 = ":10070000";
# loop throgh each line of the array &
foreach $line(@input)
{
# if the line contains your stop parameter get out
if ($line =~ /$stop1/i){
$tmp1=$line; # read one line
#read next line : How to do this?????
$tmp2=next line;
$tmp3=next line;
last;
}
}
 
$stop1 = ":10070000";
for($loop=0;$loop<@input;$loop++)
{
# if the line contains your stop parameter get out
if($input[$loop] =~ /$stop1/i){
$tmp1 = $input[$loop+1];
$tmp2= $input[$loop+2];
# This can be done in a loop as well
$i=0;
$tmp .= $input[$loop+$1] while ($i<10);
}
}
 
Just set your default input_record_seperator to ":10070000", and read the variable in as records that way

Code:
$|=":10070000";
while (<FILE>} {
  @lines=split /\n/, $_;
  &process_lines (@lines);
}

Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
you could also do something like this:

Code:
open (FILE, 'dictionary.txt') || die "can't open t.num: $!";
my @input = <FILE>;
close (FILE) || die "can't open t.hex: $!";

my $stop1 = 'geology';
my $i = -1;
for my $n (0..$#input) {
   $input[$n] =~ m/$stop1/ ? ($i = $n,last) : next;
}

if ($i > -1 && $i <= $#input-2) {
   my($temp1,$temp2,$temp3) = ($input[$i+1],$input[$i+2],$input[$i+3]);
   print "$temp1 $temp2 $temp3";
}
 
Thanks, guys.
I tried vjcyrano's srcript and it does what I want. I didn't try the other 2 yet.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top