Earlier quoted context omitted.
Do you have a good link to learn about grammars in perl?
Perl does not have grammars (at least, not built-in). Raku (formerly known as Perl 6) does: https://docs.raku.org/language/grammar_tutorial
That's not true since v5.10 (2007). Here's a sample that matches a subset of LaTeX markup:
$matcher = qr{
(?&File)
(?(DEFINE)
(? (?&Element)* )
(? \s* (?&Command)
| \s* (?&Literal)
)
(? \\ \s* (?&Literal) \s* (?&Options)? \s* (?&Args)? )
(? \[ \s* (?:(?&Option) (?:\s*,\s* (?&Option) )*)? \s* \])
(? \{ \s* (?&Element)* \s* \} )
(? \s* [^][\$&%#_{}~^\s,]+ )
(? \s* [^][\$&%#_{}~^\s]+ )
)
}xms
It's nowhere near as advanced as Raku grammars (not much is), but it's there, and it's built-in.