user17227456
user17227456

Reputation: 1317

How to flatten or stringify an object (esp. Match)?

How do we flatten or stringify Match (or else) object to be string data type (esp. in multitude ie. as array elements)? e.g.

'foobar' ~~ m{ (foo) };
say $0.WHAT;

my $foo = $0;
say $foo.WHAT
(Match)
(Match)

How to end up with (Str)?

Upvotes: 6

Views: 201

Answers (3)

jjmerelo
jjmerelo

Reputation: 23517

~ is the Str contextualizer:

'foobar' ~~ m{ (foo) };
say ~$0

will directly coerce it to a Str. You can use that if you have many matches, i. e.:

'foobar' ~~ m{ (f)(o)(o) };
say $/.map: ~*; # (f o o)

Upvotes: 7

raiph
raiph

Reputation: 32414

Just treat the objects as if they were strings.

If you apply a string operation to a value/object Raku will almost always just automatically coerce it to a string.

String operations include functions such as print and put, operators such as infix eq and ~ concatenation, methods such as .starts-with or .chop, interpolation such as "A string containing a $variable", and dedicated coercers such as .Str and Str(...).

A Match object contains an overall match. Any "children" (sub-matches) are just captures of substrings of that overall match. So there's no need to flatten anything because you can just deal with the single overall match.

A list of Match objects is a list. And a list is itself an object. If you apply a string operation to a list, you get the elements of the list stringified with a space between each element.

So:

'foobar' ~~ m{ (f) (o) (o) };
put $/;          # foo
put $/ eq 'foo'; # True
put $/ ~ 'bar';  # foobar
put $/ .chop;    # fo
put "[$/]";      # [foo]
put $/ .Str;     # foo

my Str() $foo = $/;
say $foo.WHAT;   # (Str)

put 'foofoo' ~~ m:g{ (f) (o) (o) }; # foo foo

Upvotes: 5

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

The constructor for Str takes any Cool value as argument, including a regex Match object.

'foobar' ~~ m{ (foo) };
say $0.WHAT; # (Match)
say $0.Str.WHAT; # (Str)

Upvotes: 5

Related Questions