It's very useful to 'factor' regexes as one would factor subroutines. The relationships of the parts to each other and to the whole are clarified, and it becomes easier to change a part when necessary. This clarity and ease of maintenance can be important for complex regexes (or for simple regexes when you're trying to debug one at 3 AM!).
>perl -wMstrict -le "my $prefix = qr{ (?i) \b tbgl_ }xms; my $word = qr{ \w+ }xms; my $suffix = '_gl'; ;; print '--- output ---'; for my $pw (@ARGV) { (my $ws = $pw) =~ s{ $prefix ($word) }{$1$suffix}xmsg; print qq{'$pw' -> '$ws'}; } " "tbgl_foo xxx %$# tbgl_bar()" "TBGL_foo tBgL_bar" "tbgl tbglfoo tbgl_" "tbgl_%$# Xtbgl_foo" --- output --- 'tbgl_foo xxx %$# tbgl_bar()' -> 'foo_gl xxx %$# bar_gl()' 'TBGL_foo tBgL_bar' -> 'foo_gl bar_gl' 'tbgl tbglfoo tbgl_' -> 'tbgl tbglfoo tbgl_' 'tbgl_%$# Xtbgl_foo' -> 'tbgl_%$# Xtbgl_foo'
In the example above, it was only necessary to change the definition of $prefix from
my $prefix = qr{ \b tbgl_ }xms;
to
my $prefix = qr{ (?i) \b tbgl_ }xms;
when somebody said "Oh, by the way, the prefix pattern is supposed to be case insensitive."
One could use the /i regex modifier (see Modifiers in perlre) instead of the (?i) extended pattern (see Extended Patterns in perlre) to make $prefix case insensitive, but the latter is less easy to overlook.
In reply to Re: regex replace problem
by AnomalousMonk
in thread regex replace problem
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |