Perl newbie - regex replace all groups issue

Hello,

Although I have found similar questions, I could not find
advice that could help with my problem. The issue:

I am trying to replace all occurrences of a regex, but
I cannot make the regex groups work together.

This is a simple input test file:

The Vedanta Philosophy
~~~~~~~~~~~~~~~

Body text

This is what the output should be:

## The Vedanta Philosophy

Body text

This is my code:

#!/usr/bin/perl -w

use strict;

while (<>) {
    s/(^.*)\n(^~+)/## $1/igm;
    print;
}


sub usage {
    (my $progname = $0) =~ s/.*[\\\/]//;
    die "Usage: $progname [<file>...]\n";
}

The two groups

(^.*)

and

(^~+)

match the test file independently, but when
I put them together in the s///igm line, they do not work at all.

I read the perl regex introduction and tutorial, and
searched for hints where I am making a mistake, with no avail.

:wall:

Thank you for any help or indication on how to solve this problem.

Hi samask,

Some issues:

1.- while (<>) reads one line at a time and your regex tries to work over multiple lines.
2.- '^' marks the beginning of the line and it is zero-width, put it out of the parentheses.
3.- There is no need of the 'g' switch. Your regex only will match at most once.
4.- No need of 'i' switch. You are not using any alphabetic character.

One solution:

$ cat script.pl
use warnings;
use strict;

local $/;
my $file = <>;
$file =~ s/^(.*)\n^(~+)/## $1/m;
print $file;
$ cat infile
The Vedanta Philosophy
~~~~~~~~~~~~~~~

Body text
$ perl script.pl infile
## The Vedanta Philosophy

Body text

Regards,
Birei

you can do below if interested with one liner:-

perl -07 -wlpe 's/(.*)\s+~+/## $1/s ;' infile.txt

:D:D:D

Wow, thank you so much birei!

Thank you for the explanation, and also for your code.
It is just elegant, and it works perfectly.

Thank you so much once again.

Sam

---------- Post updated at 11:31 ---------- Previous update was at 11:29 ----------

Thank you ahmad.diab!

I like one liners, but, as I will add more regex logic, it may be more practical as separate script.

Thank you!

Sam