I am used to Perl but a Perl 6 newbie
我习惯了Perl,但不习惯Perl 6新手
I want to host a regular expression in a text variable, like I would have done in perl5:
我想在文本变量中托管正则表达式,就像在perl5中那样:
my $a = 'abababa';
my $b = '^aba';
if ($a =~ m/$b/) {
print "True\n";
} else {
print "False\n";
}
But if I do the same in Perl6 it doesn't work:
但如果我在Perl6中做同样的事,那就行不通了:
my $a = 'abababa';
my $b = '^aba';
say so $a ~~ /^aba/; # True
say so $a ~~ /$b/; # False
I'm puzzled... What am I missing?
我困惑……我缺少什么?
2 个解决方案
#1
5
You need to have a closer look at Quoting Constructs.
您需要更仔细地查看引用构造。
For this case, enclose the part of the LHS that is a separate token with angle brackets or <{
and }>
:
对于这种情况,将作为尖括号或<{和}>的独立标记的LHS部分括起来:
my $a = 'abababa';
my $b = '^aba';
say so $a ~~ /<$b>/; # True, starts with aba
say so $a ~~ /<{$b}>/; # True, starts with aba
my $c = '<[0..5]>'
say so $a ~~ /<$c>/; # False, no digits 1 to 5 in $a
say so $a ~~ /<{$c}>/; # False, no digits 1 to 5 in $a
Another story is when you need to pass a variable into a limiting quantifier. That is where you need to only use braces:
另一种情况是,需要将变量传递给一个限定量词。这就是你只需要使用括号的地方:
my $ok = "12345678";
my $not_ok = "1234567";
my $min = 8;
say so $ok ~~ / ^ \d ** {$min .. *} $ /; # True, the string consists of 8 or more digits
say so $not_ok ~~ / ^ \d ** {$min .. *} $ /; # False, there are 7 digits only
#2
4
Is there a reason why you don't pick the regex object for these types of uses?
为什么不为这些类型的用途选择regex对象?
my $a = 'abababa';
my $b = rx/^aba/;
say so $a ~~ /^aba/; # True
say so $a ~~ $b; # True
#1
5
You need to have a closer look at Quoting Constructs.
您需要更仔细地查看引用构造。
For this case, enclose the part of the LHS that is a separate token with angle brackets or <{
and }>
:
对于这种情况,将作为尖括号或<{和}>的独立标记的LHS部分括起来:
my $a = 'abababa';
my $b = '^aba';
say so $a ~~ /<$b>/; # True, starts with aba
say so $a ~~ /<{$b}>/; # True, starts with aba
my $c = '<[0..5]>'
say so $a ~~ /<$c>/; # False, no digits 1 to 5 in $a
say so $a ~~ /<{$c}>/; # False, no digits 1 to 5 in $a
Another story is when you need to pass a variable into a limiting quantifier. That is where you need to only use braces:
另一种情况是,需要将变量传递给一个限定量词。这就是你只需要使用括号的地方:
my $ok = "12345678";
my $not_ok = "1234567";
my $min = 8;
say so $ok ~~ / ^ \d ** {$min .. *} $ /; # True, the string consists of 8 or more digits
say so $not_ok ~~ / ^ \d ** {$min .. *} $ /; # False, there are 7 digits only
#2
4
Is there a reason why you don't pick the regex object for these types of uses?
为什么不为这些类型的用途选择regex对象?
my $a = 'abababa';
my $b = rx/^aba/;
say so $a ~~ /^aba/; # True
say so $a ~~ $b; # True