jan jan - 4 months ago 19
Perl Question

Perl regex to transform line based on information in line above

I am trying to outcomment two lines, one following the other, of a text file as part of a perl script. The first line always starts with

so it's easy to write a regex that finds it but the second line can be any random text so I'm trying to use one regex to match the first line, a linebreak
and then any stuff that comes after that until the next linebreak. But I can't get it to match more than the first line.

s/^(file:\/\/\/.*)\n(.*)/\% $1\n\% $2/g;

Help much appreciated!


Perhaps this is what you need:

my $data = "Smth\nfile:///myfile\nstring\nsmthelse\n";
$data =~ s/(file:\/\/\/.*?)\n(.*?)\n/\% $1\n\% $2\n/s;
print $data


% file:///myfile
% string

So you can read a file into one string like: my $str = join '', <$fh> and do regexp with s key to process it as single line. Read

If you do some stuff with every line and besides you want to change mentioned two lines as I did above, you can do so:

$data =~ s/(file:\/\/\/.*?)\n(.*?)\n/\% $1\n\% $2\n/s;
$file_str = $1;
$afterfile_str = $2;
my @data_arr = split /\n/, $data;
for(@data_arr) {
    # some code, perhaps using $file_str and $afterfile_str
    print $fh_out $_  . "\n";