Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto Work with Record Separator in Perl

Tags:

linux

unix

perl

I have a data that looks like this

--
read50_1: read1391364_2,read3529226_1,
--
read46_2: read916_1,read178252_2,read1336397_1,read1824459_2,
read916_1: read0_1
--
read34_1: read209771_2,
--
read32_2: read520377_2,

What I want to do is to access the entry excluding the record separator "--".

But why this code doesn't do it?

my  $INFILE_file_name = "myfile.txt";      # input file name
my $content = '';
open ( INFILE, '<', $INFILE_file_name )
    or croak "$0 : failed to open input file $INFILE_file_name : $!\n";

{
    local $/ = "--";

    $content = <INFILE>;
    print "$content\n";

}

close ( INFILE );           # close input file
like image 911
neversaint Avatar asked Dec 16 '22 19:12

neversaint


2 Answers

First of all, I'm guessing you meant

local $/ = "--\n"; # or maybe "\n--\n"

(If you do use "\n--\n", then the first line will no longer be considered a record separator, but will be part of the first record. You might want to read that first -- line before changing $/.)

Remember that $/ is not removed by the <IN> operator. Use chomp to do that.

Secondly, the file begins with the record separator, so the first record will be blank.

{
    local $/ = "--\n";

    while ($content = <INFILE>) {
      chomp $content;
      print "$content\n" if $content; # Skip empty records
    }
}
like image 53
cjm Avatar answered Jan 01 '23 07:01

cjm


You could also just do:

while(<INFILE>) {
        print unless(/\s*--\s*/);
}
like image 36
codaddict Avatar answered Jan 01 '23 07:01

codaddict