Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: s///g within m//g regions

by haukex (Bishop)
on Nov 09, 2021 at 14:22 UTC ( #11138621=note: print w/replies, xml ) Need Help??


in reply to s///g within m//g regions

There are quite a few techniques you can use to make your regexen nicer, any combination of which might be useful to you, see for example /x, /e, /r, \K, and lookarounds in perlre. In the following example I've thrown all of them together into one, which may be overkill. (I see ikegami has posted something similar, albeit non-functional, while I was composing this.)

my $data = <<'END'; foo123bar # foo123bar foo456bar # xyz foo789bar abc foo456bar END $data =~ s{ ^ # beginning of line \h* \# \h* # comment lines \K # keep everything up to here in replacement (?<comment> \N*) # capture the comment $ # end of line } { handle_foobar( $+{comment} ) }msxge; sub handle_foobar { return shift =~ s{ foo \K (\d+) (?= bar ) }{ $1 =~ tr/0-9/a-j/r }msxger; }
I could turn the string into a line-list

Note it's also possible to open a string as an in-memory filehandle:

my $str = <<'END'; Hello # START World # END Aaa # START Bbb # END Ccc END open my $fh, '<', \$str or die $!; while (<$fh>) { chomp; if ( /^# START/ .. /^# END/ ) { print "<$_>\n"; } } close $fh;

Also, a more advanced regex technique is m/\G.../gc parsing, which is described in perlop. Also, as for your example here, if the delimiters need to be escaped, see Regexp::Common::delimited.

Replies are listed 'Best First'.
Re^2: s///g within m//g regions
by almr (Acolyte) on Nov 09, 2021 at 21:52 UTC
    Thanks for inventorying all these techniques. The basic thing I was forgetting was the /e modifier, combined with using s{}{} as a delimiter. This is a really powerful combination!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138621]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2022-01-24 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:












    Results (64 votes). Check out past polls.

    Notices?