6

In P5, I am able to do something like this

my ($var1, $var2, $var3) = $string =~ /(.+)\s(.+)\s(.+)/;

How do I do the same in Perl 6? If I do the same syntax, the $var1 will hold the entire $string value.

Zarul Zakuan
  • 510
  • 3
  • 13

2 Answers2

8

The result from that match is a Match object, which by itself won't behave like a list, and therefore won't expand into the three variables. However, the Match object has a "list" method that does what you want. Here's an example:

my $string = "hello how are you";
my ($var1, $var2, $var3) =
    ($string ~~ /(.+)\s(.+)\s(.+)/).list;
say "$var1 and $var2 and $var3
# Output: hello how and are and you

A few further things to point out:

  • Since .+ is a greedy match, and it also accepts spaces, the first capture will eat up two words.
  • Surely the code in the question is a simplified example, but if you ever need to split text into words, maybe the words method does what you want. Of course, you'll want to check what exactly you want: Split by spaces? Only return alphabetic characters, so that periods and commas aren't in the final result? etc.
  • If you do need to match the same thing multiple times, maybe the comb method is actually more helpful?
timotimo
  • 4,299
  • 19
  • 23
  • 1
    ive been using P6 for like less than a week now and I got a sense that this is not Perl at all :-) – Zarul Zakuan Nov 25 '18 at 05:29
  • It *is* like Perl5 in a lot of way but yes if you expect it to work exactly the same way you'll maybe trip up a few times. I can recommend looking at https://docs.perl6.org/language/5to6-nutshell the Perl5 to Perl6 guide for pointers :) – Scimon Proctor Nov 25 '18 at 20:26
7
my $string = 'foo bar baz';

my $match = $string ~~ /(.+)\s(.+)\s(.+)/;
say $match;     # 'foo bar baz'
say $match[0];  # 'foo'
say $match[1];  # 'bar'
say $match[2];  # 'baz'

my ($foo, $bar, $baz) = @$match;
say $foo;       # 'foo'
say $bar;       # 'bar'
say $baz;       # 'baz'

therefore

my ($foo, $bar, $baz) = @($string ~~ /(.+)\s(.+)\s(.+)/);
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 1
    Thanks Tomalak. On a different note, why $match[0] if its an array? I thought in P6 the sigil now changed to @ ? – Zarul Zakuan Nov 25 '18 at 02:59
  • 1
    That's right, but in perl 6 there are no longer references, so you don't have to dereference the list object in order to access its individual elements via subscript. – timotimo Nov 25 '18 at 03:03
  • 1
    i like this method instead of .list. this is more Perl-ish :-) Thanks! – Zarul Zakuan Nov 25 '18 at 05:32