[olug] Offtopic: Perl question - read file in for loop

Matt Anderson manderso at cs.wisc.edu
Thu Feb 16 14:52:15 UTC 2006


Would something like this get the job done?  I'm not sure you really  
need the nested loop for what you seem to be trying to do.

--

$found_pattern_one = 0;
$result = "nothing";
foreach (<STDIN>) {
     chomp;
     unless ($found_pattern_one) {
         if (/pattern1/) {$found_pattern_one = 1;}
     } else {
         if (/pattern2/) {result = $_; last;}
     }
}

print $result;

--
  Matt Anderson


On Feb 15, 2006, at 8:27 PM, Eric Penne wrote:

> I have a Perl problem.
>
> I do multiple tests in this one file but I only want to know if a  
> certain one passes or fails.  The footer is 20 lines.  At the  
> beginning it says:
>
> End Report ESS Cyclic
>
> In the next 20 lines it says the end date and the result.
>
> I can do it with an array and by using shift but the files can be  
> pretty large and I don't want to take up that memory resource.  I  
> tried just readng thefile line by line then putting a for loop with  
> 20 counts in it.
>
> a rough snippet follows.  I tried to include all the times I modify  
> the $LINE variable and I skipped a lot of blocking.
>
> foreach $LINE (<File>)
> 	chomp $LINE
> 	if ($LINE =~ /pattern1/}
> 		for ($i=1; $i<=20; $i++)
> 			$LINE=<File>
> 			chomp $LINE
> 			if ($LINE =~ /pattern2/)
> 				$RESULT= split $LINE
>
>
> but on the $LINE=<FILE> it always says there is nothing there and I  
> get errors from the -w option with perl.  I do know that the line  
> immediately after pattern1 is blank.  If I print $LINE at that  
> point it always comes out blank and it prints 20 blank lines.
>
> Shouldn't each iteration through the for loop tell it to grab the  
> next line?
>
> BTW,  extreme newbie to perl.  1st usuable script only took 8 hours  
> but it should save me that over the next 2 weeks.
>
> Thanks
> Eric Penne
>
>
>
>
> jbeattie at z9.net wrote:
>> Greetings
>> We plan to meet next Thursday Feb 2. I would be interested in
>> anyone who is using Asterisk and how it was implemented.
>> The book is a free download.
>> http://www.crlug.org/mediawiki/index.php/Asterisk
>> Other topic ideas welcome as always.
>> for more information www.crlug.org
>> See you there
>> Thanks
>> -Jay
>> _______________________________________________
>> Listserv mailing list
>> Listserv at iowalug.org
>> http://mail.iowalug.org/mailman/listinfo/listserv
> _______________________________________________
> OLUG mailing list
> OLUG at olug.org
> http://lists.olug.org/mailman/listinfo/olug




More information about the OLUG mailing list