πŸŽ„ 24/25. Reading files with $*ARGFILES in Perl 6

Welcome to Day 24 of the Perl 6 One-Liner Advent Calendar!

In the previous days, we were reading text files, so it would be logical to talk about $*ARGFILES, a built-in dynamic variable that may be handy when working with multiple input files.

How do you read two or more files passed in the command-line?

$ perl6 work.pl a.txt b.txt

If you need to process all the files together as if they would be a single data source, you could ask our today’s variable to do the job in a one-liner:

.say for $*ARGFILES.lines

Inside the program, you don’t have to think about looping over the files; $*ARGFILES will automatically do that for you.

If there are no files in the command line, the variable will be attached to STDIN:

$ cat a.txt b.txt | perl6 work.plΒ 

Handy indeed, isn’t it?

6.d and MAIN

I also have to warn you if you will want to use it in bigger programs. Consider the following program:

sub MAIN(*@files) {
.say for $*ARGFILES.lines;
}

In Perl 6.d, $*ARGFILES works differently inside the MAIN subroutine and outside of it.

This program will perfectly work with Perl 6.c, but not under Perl 6.d. In other words, in Rakudo Star up to and including version 2018.10, $*ARGFILES handles filenames in the command line, but starting with Rakudo Star 2018.12, it will be always connected to $*IN if it is used inside MAIN.

And that’s the end of today’s advent post and almost the end of the whole calendar of this year. Nevertheless, come again tomorrow!

2 thoughts on “πŸŽ„ 24/25. Reading files with $*ARGFILES in Perl 6”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s