I have some long lines and I want to highlight the matches with colors that I want. One function uses substitution, and the other function uses recursion. Some works and some don't; I am looking for a consistent way to interpolating into regex. Thank you very much !!!
sub colorMatch ($aStr, $aRegex, $aColor) {
my $colorOff = '\e[0m';
my $a =$aStr.subst(/(<{$aRegex}>)/, $aColor ~ "# $/ #" ~ $colorOff, :g);
# not working, $/ not interpolating corresponding matches, all Nil
say $a;
}
colorMatch("a-12-b-3-c-4-def-567", '\d+', '\e[1;31m');
colorMatch("a-12-b-3-c-4-def-567", '<alpha>+', '\e[1;31m');
say "\e[1;31m" ~ " color1 " ~ "\e[0m" ~
"\e[1;36m" ~ " color2 " ~ "\e[0m";
sub colorMatch2 ($aStr, $aRegex, $colorNumber) {
my $colorOff = "\e[0m";
if $aStr.chars > 0 {
my $x1 = ($aStr ~~ m/<{$aRegex}>/);
my $x2 = $x1.prematch;
my $x3 = $x1.Str;
my $x4 = $x1.postmatch;
return ($x2 ~ "\e[1;{$colorNumber}m" ~ $x3 ~ $colorOff)
~ colorMatch2($x4, $aRegex, $colorNumber);
}
}
say colorMatch2("a-12-b-3-c-4-def-567", '\d+', 31); # works, red color
say colorMatch2("a-12-b-3-c-4-def-567", '567', 36); # works, green color
say colorMatch2("a-12-b-3-c-4-def-567", '\w+', 31); # works, red color
say colorMatch2("a-12-b-3-c-4-def-567", '[a..z]+', 31); # fails with [] and ..
say colorMatch2("a-12-b-3-c-4-def-567", "<alpha>+", 31); # fails with <>
Use of Nil in string context
in sub colorMatch at colorMatch.pl line 4
a-\e[1;31m# #\e[0m-b-\e[1;31m# #\e[0m-c-\e[1;31m# #\e[0m-def-\e[1;31m# #\e[0m
# seems to do substitution, but $/ is empty and color not shown;
Use of Nil in string context
in sub colorMatch at colorMatch.pl line 4
\e[1;31m# #\e[0m-12-\e[1;31m# #\e[0m-3-\e[1;31m# #\e[0m-4-\e[1;31m# #\e[0m-567
# seems to do substitution, but $/ is empty and color not shown;
color1 color2 # both colors work and shown as expected,
# color1 red and color 2 green; why inconsistent with above???
a-12-b-3-c-4-def-567 # works, red color
a-12-b-3-c-4-def-567 # works, green color
a-12-b-3-c-4-def-567 # works, red color
No such method 'prematch' for invocant of type 'Bool'
in sub colorMatch2 at colorMatch.pl line 17
in block <unit> at colorMatch.pl line 28