perl6有色匹配,一些正则表达式插值有效,有些则没有;颜色代码不一致

我有一些长队,我想用我想要的颜色突出显示匹配.一个函数使用替换,另一个函数使用递归.有些是作品,有些则没有;我正在寻找一种插入到正则表达式的一致方法.非常感谢你 !!!

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,$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,$colorNumber);
    }
}

say colorMatch2("a-12-b-3-c-4-def-567",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+','[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

解决方法

这不是插值问题.字符类和范围的语法略有不同.你需要:

'text' ~~ / <[a..z]>+ /

至于你在bool上调用prematch()的其他错误,结果是False,因为在最终的递归级别,它不再匹配.在假设匹配之前,您需要检查结果.

最后,对于“在字符串上下文中使用Nil”,这是因为您使用的是Str.subst,并且与大多数语言中的大多数函数调用一样,在函数开始之前会对参数进行求值.你在参数中使用$/,但它还没有设置,因为函数的主体甚至没有开始执行. s / match / replacement /运算符不会遇到这种困难,所以我建议你将代码更改为:

$aStr ~~ s:g/(<$aRegex>)/$aColor# $/ #$colorOff/;

(或者为了更好的可读性:)

$aStr ~~ s:g {(<$aRegex>)} = "$aColor# $/ #$colorOff";

这假设您已将$aRegex变为正则表达式而不是字符串.此外,由于新代码修改了$aStr,您需要将$aStr更改为$aStr是函数签名中的副本.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...