It’s blocks all the way down
While playing with Perl 6 on glot.io I learned that they really like docker with the simple program:
dir('/')>>.Str.say;
And I wondered if there is a nice idiom for recursing into directories. IO::Path.dir
will return a Seq
of IO::Path
objects. That’s why the >>
. hyperoperator works. It wont recurse of cause as there is no sub to recurse with. After some open eye meditation I found what I was looking for quite some time.
A block in Perl 6 is a Callable with one positional argument. That argument is bound to the topic $_
. That’s why we can do:
for 1,2,3 { .say }
Recursing into a directory would be easy if we turn the Str
'/'
into a IO::Path
object and check if we got a directory and call the block with that element. That block would need a name, what we could do with my &block = { Nil }
, or we use the compile time variable &?BLOCK
.
for '.' { .Str.say when !.IO.d; .IO.dir()>>.&?BLOCK when .IO.d }
The form .&?BLOCK
will treat the call like a method call, what means the object left of .
will be the first parameter of the call, where the invocant belongs.
I believe this is a fairly nice example how to use &?BLOCK
to get rid of nested loops and one shot variables. It will be added shortly to the docs.
With the kind help of Zoffix the example was golfed down further.
{ .d && .dir».&?BLOCK || .put }(".".IO)
Perl 6 can recurse with the best of them. :)
-
July 25, 2016 at 23:192016.30 Fresh Rakudo Star! | Weekly changes in and around Perl 6