2 ms·
One way in P6: say ~ m/ '@' (.*) / for lines Ignoring the regex for now (the `/.../` bit), this reads as say (`say`) the string (`~`) that matches (`m`) f
by raiph 12y ago
One way in P6:
say ~ m/ '@' (.*) / for lines
Ignoring the regex for now (the `/.../` bit), this reads as say (`say`) the string (`~`) that matches (`m`) for each of (`for`) the lines (`lines`).
Note that lists (`lines` returns a list) are lazy by default in P6. So the above code will start producing results immediately and continue without exhausting RAM even if the input is infinite.
The `/ ... /` bit above is a "regex". It means match the symbol '@' and return all the following characters of that line. P6 regexes are far more powerful than P5 regexes. P6 regexes can work together to comprise arbitrarily complex parsing grammars. The main P6 compiler, Rakudo, parses input source code using a P6 grammar.
There are of course many more ways:
say lines.map: { m/ '@' /; $/.postmatch ~ "\n" }
In this instance `lines` is treated as an "object" (a `List` in this case) on which the `map` "method" is called. `map` calls the block of code (the `{...}` bit) against each element in its invocant, ie against each line. The block of code matches a '@' and returns whatever follows it ("postmatch") with a newline appended. (`$/` refers to "the match object"; it's one of three symbolically named variables in P6 as against the dozens in Perl 5.)