in reply to How do you read the next line in a file while in a loop?

Wow, what an awesome amount of code! I don't think you've sat down and figured out the algorithm. What do you really want the script to do? The way I understand it (and I may have misinterpreted it, but bear with me)... You have a text file that contains data and comments. You want to strip out the comments. The data you are interested in is introduced by the word "on" (case-insensitive). It may span several lines, if so, a trailing comma indicates that there's more to get on the subsequent line.

Now here's that part that you haven't thought through... how are you going to know when to stop? The way I see it is that you grab the line with "on" and isolate the part that interests you. Once you have this, now, and for any subsequent line you read, if what you have ends in a comma, then you want to get the next line. Eventually, you will append a line that does not have a trailing comma, in which case you stop.

Once you know how things are supposed to behave, the code usually follows naturally.

#! /usr/bin/perl -w use strict; my $want_next_line = 0; my $on = ''; while( <DATA> ) { chomp; # never use chop s/\s*#.*$//; # discard comments next unless $_; # go to next line if nothing left if( /^on (.*)$/i ) { $on = $1; } elsif( $want_next_line ) { $on .= $_; } $want_next_line = $on =~ /,$/ ? 1 : 0; } $on =~ s/\s//g; print "\$on = $on\n"; __DATA__ INPUT FILE = # comment # comment ON Mon, Tues, Fri, Sat # comment other stuff

As you can see, if you can state the problem clearly, the code usually falls out nicely.

--
g r i n d e r

Replies are listed 'Best First'.
Re: Re: How do you read the next line in a file while in a loop?
by GroundZero (Initiate) on Aug 31, 2001 at 03:10 UTC
    Thanks Grinder, This is exactly what I was looking for. Although I was probally using fuzzy logic. i.e. I had thought out the algorithm but did not code it as clearly. Thanks again for your help.