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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read in values from middle of file

Status
Not open for further replies.

Ito2233

MIS
Sep 2, 2003
77
US
I have a dat file looking like this:
__________
Running totals:
Question 1: 60
Question 2: 123
Question 3: 99

Averages:
Question 1: 4.6
Question 2: 9.5
Question 3: 7.6
___________

I have a code to store the Running totals into a hash, such as the following:

my %hash; my $key; my $value;
open(ANSWERTALLY, "answertally.dat");
while(ANSWERTALLY n) {
($key, $value) = split(/\s=\s/);
chomp($value);
$hash{$key} = $value;
}
close(ANSWERTALLY);

However, this code will try to read everything in the file. How can I tell it to skip the first line (RUNNING TOTALS), and stop executing when it encounters AVERAGES:???
I'm not too good with string manipulation or regular expressions.

Thanks
 
I'm not sure if this is the best way, but it does work.. I assumed you wanted to split on the colon, so I changed that regex
Code:
while (<ANSWERTALLY>){
   last if /^Averages:/;
   next if /^(Running totals:|\s*$)/; 
   chomp;
   ($key, $value) = split(/:/);
   $hash{$key} = $value;
}
The 'last' statement exits the while loop if the line begins with "Averages:"
The 'next' statement skips the line if it begins with "Running totals:", or if there's a blank line
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top