8

I am used to Perl but a Perl 6 newbie

I want to host a regular expression in a text variable, like I would have done in 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:

my $a = 'abababa';
my $b = '^aba';

say so $a ~~ /^aba/;  # True
say so $a ~~ /$b/;    # False

I'm puzzled... What am I missing?

Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
mmzz
  • 81
  • 2

2 Answers2

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 }>:

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

enter image description here

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

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you, but that doesent work, the expression matches everything: – mmzz Aug 05 '17 at 08:30
  • @mmzz Please explain what you mean. Didn't you want to get True as output for the `'abababa'` string? – Wiktor Stribiżew Aug 05 '17 at 14:13
  • @viktor-stribiżew yes indeed, but with ${b} I got True with any pattern, even "xxxx". my $a = 'abababa'; my $c = 'xxxxxxx'; say so $a ~~ /{$c}/; #True – mmzz Aug 07 '17 at 08:34
4

Is there a reason why you don't pick the regex object for these types of uses?

my $a = 'abababa';
my $b = rx/^aba/;

say so $a ~~ /^aba/;  # True
say so $a ~~ $b;     # True
nxadm
  • 2,079
  • 12
  • 17