indir() changes the directory just for its block

Update for April 2017: indir is now a documented part of the language.

How many times have I wanted to change the current working directory for just one block? It’s usually such a pain because I have to remember to change it back.

In Perl 6, the indir routine does this for me:

indir $some_dir, {
    ...; # do stuff in that directory

The current working directory is changed just for that block of code. When that block is done, the value is back to whatever it was before. That this is built into the language is quite pleasing to me (and the dependency-adverse contexts I tend to work in). There’s no variable to mess with (in Perl 6 that would be $*CWD, which has some issues at the moment) and it reads nicely as a sentence.

This isn’t documented yet (it only shows up in Synopsis 16, last changed 10 years ago, and was announced as part of 2014.10), but it’s in there and it mostly works. At the moment (Rakudo 2016.11) it only works when the target directory is readable and writeable, but I’ve filed RT #130460 about that. And, I’ve filed GitHub #1091 about the lack of documentation (which depends on someone declaring what it should actually do). Since it’s untested and undocumented, that means it might change or disappear. Consider that before you get too excited. But, how can you not get excited about something that makes common things really easy?

I feel a little bad that I’m not stopping to fully investigate these corner cases, but if I did that I’d never get any writing done for Learning Perl 6! Maybe someone else has the time to make this bit of Perl 6 tested and documented.


  1. I don’t know why brian is writing about stuff that’s not part of Perl 6 language. The invitation to document and test this routine is misleading, as the current incantation is undesirable and your PR testing or documenting it will be rejected.

    1. An update: indir is now part of the language. Several of the features have changed this this post was posted, but the post does not talk about them, so everything described here is still valid.

Leave a Reply

Your email address will not be published. Required fields are marked *