Perl "=+\n" as $/ separator

Viewed 101

Sorry for a stupid question, but I'm a beginner, so I can't sort out this problem.

I work with files where chunks of data are divided by lines of consecutive = signs of different length, followed by \n. I want to read these chunks as separate records, using $/ = "=+\n"; But it doesn't detect the === separator.

So my code is:

$ cat prog1 
#!/usr/bin/perl

use v5.22;
use strict;
use warnings;

$/ = "=+\n";
$\="+++\n";

while (<>){
  chomp;
  print;
}

My data:

$ cat data1 
line1
line2
===
line4
line5

My output:

$ ./prog1 data1 
line1
line2
===
line4
line5
+++
2 Answers

$/ doesn't support regular expressions. You'll need to use ===\n.

You can use a regex to pseudo-chomp using a regex though.

#!/usr/bin/env perl
use strict;
use warnings;


$/ = "=\n";
$\="+++\n";

while (<>){
  s/^=+\n\z//gm;
  print;
}

See: perlvar:

the value of $/ is a string, not a regex.

If the file is short enough, load it into memory and split on whatever end-of-record indicator you want:

local $/;
my @lines = split /=+\n|\++\n/, <>;
foreach my $line (@lines) { ... }

If it is important what the record separator was (say, if you need to distinguish records that end with ===\n from records that end with +++\n), capture the record separator

local $/;
my @lines = split /(=+\n|\++\n)/, <>;
while (my $line = shift @lines) {
    my $record_separator = shift @lines;
    ...
}
Related