> -----Original Message-----
> From: Vitali [mailto:[EMAIL PROTECTED]]
> Sent: Monday, March 04, 2002 6:58 AM
> To: [EMAIL PROTECTED]; [EMAIL PROTECTED]
> Subject: Lines count...how to..
> 
> 
> Dear friends,
> can anybody correct me...I have a text file.Data look like this:
> 10
> 20
> 20
> 20
> 20
> 10
> 20
> 20
> 10
> 20
> 20
> 20
> and so one
> -------------------------------------------------
> while (<STDIN>) {
> if  (substr($_,0,2) eq "10")  {           #If left 2 
> characters is 10,then
> .....
>   ++$count;
>   $lines = 0;
>   open  OUT, ">$count.out";

I'm not sure what you're trying to do here.

>   print OUT $_;                   };
> 
> if  (substr($_,0,2) eq "20")    {          #If left 2 
> characters is 20,then
> .....
>     ++$lines;                                     #Counts he lines
>     if ($lines == 4){ print OUT "Someinfo\n";$lines = 0;};
>     print OUT $_;};
> 
>   }
>  __EOF__
> 
> Now is: if lines count of type "20" is 4, print "Someinfo" 
> after 4 line.
> How I can fix the code, if lines count of type "20" is less 
> that 4(for exp
> 1,or 2,or 3), and I need print "Something" after last line of "20"?
> Here is example of how to output must be look.
> 
> 10
> 20
> 20
> 20
> 20
> Someinfo
> 10
> 20
> 20
> Someinfo
> 10
> 20
> 20
> 20
> Someinfo
> 10
> 20
> 20
> 20
> 20
> Someinfo
> 20
> 20
> 20
> 20
> Someinfo
> 20
> 20
> 20
> 20
> Someinfo

If I understand correctly, the requirement is to print "Someinfo"
after every four consecutive 20's, or when switching from a 20 line
to a non-20 line. If so, here's one approach that should work:

  #!/usr/bin/perl
  use strict;

  my $count20 = 0;

  while(1) {
      # read next line (undef on eof)
      $_ = <>;

      # see if current line is a "20"
      my $is20 = substr($_, 0, 2) eq '20';

      # print marker after 4 consecutive "20"'s,
      # or when we switch to a non-"20"
      print "Someinfo\n"
          if $count20 == 4
          || ($count20 && !$is20);

      # stop when eof reached
      last unless defined $_;

      # adjust count
      $count20 = $is20 ? ($count20 % 4 + 1) : 0;

      # emit current line
      print;
  }

I'm using a while(1) loop instead of a while(<>) loop, because
we may need to emit "Someinfo" after the last line is read, and
I didn't want to duplicate the code outside the loop.   

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to