Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

Reading multi-line records

Given the code data file content of each data records, I'm unable to print the first line of each record. However, it does print the first line of the first record as in: 1aaaaaaaaaaaaa

Special Note: I'm sure there are many ways to do this, but in my case, I need a solution that follows the code question....

Data file content of records

  1aaaaaaaaaa 
  aaaaaaaaaaa 
  aaaaaaaaaaa 
  __Data__ 
  1bbbbbbbbbb 
  bbbbbbbbbbb 
  bbbbbbbbbbb 
  __Data__ 
  1cccccccccc 
  ccccccccccc 
  ccccccccccc 
  __Data__

  { 
      local $/="__Data__\n"; 

      open my $fh,"<","logA.txt" or die "Unable to open file"; 

      while(<$fh>) 
      { 
        # remove the input record separator value of __Data__\n
        chomp; 

        # display the line of each record 
        if(/([^\n]*)\n(.*)/sm) 
        { 
           print "$1\n"; 
        } 
      } 
      close ($fh); 
  } 

I get the undesirable output of:

  [root@yeti]# perl test2.pl    
  1aaaaaaaaaaaaa
  [root@yeti]#

I need the output of the first line of each record.....

1aaaaaaaaaaa 1bbbbbbbbbbb 1ccccccccccc

Upvotes: 0

Views: 129

Answers (1)

ikegami
ikegami

Reputation: 386351

To debug, you find where the state of the program diverges from your expectations, then you backtracking until you find the cause.

Checking what the program does reveals that your loop is only entered once and that $_ contains the entire file. That means that Perl didn't find the line terminator ("__Data__\n").

Examining the file finds spaces between __Data__ and the newline. Remove the trailing spaces from your file.

perl -i -ple's/\s+\z//' logA.txt

Upvotes: 2

Related Questions