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

๐ŸŽ„ 24/25. Reading files with $*ARGFILES in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


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!

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

  1. Hi there,

    Could you go over how to use globbing from the command line?

    First pass: raku -n -e “.say” *.txt

    It says: Failed to open file C:\..\*.file: Invalid Argument

    Second pass: raku -e “.say for $*ARGFILES.lines” *.txt

    Same error.

    A naive attempt to use the IO::Glob module:

    raku -e “use IO::Glob; .say for glob($*ARGFILES.Str)” *.file

    Same error.

    Pretty surprised my attempts are all crashing and burning – perl grew up on the command line. But this also might be a windows bug / feature..

Leave a Reply

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

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code