Taylor Lee
Taylor Lee

Reputation: 113

Perl 6 iterate through command line arguments

I want to write a Perl 6 program that performs the same operation on an undetermined number of files, just like how you can use rm file1.txt file2.txt file3.txt in Linux.

My code looks like this:

#!/usr/bin/env perl6


my @args = @*ARGS.perl;

for @args -> $arg {
    say $arg
}

However, when I invoke it as ./loop_args.pl6 file1.txt file2.txt I get the following output: ["file1.txt", "file2.txt"]

What am I doing wrong? I just want it to be an array.

Upvotes: 10

Views: 801

Answers (2)

Scimon Proctor
Scimon Proctor

Reputation: 4558

So it depends on what you want to do with the files. If you want to read through them all you might want to take a look at $*ARGFILES this is an IO::CatHandle Object that batches up all the arguments and treats them as a list of files. So to print them all out you could do.

#! /usr/bin/env perl6
use v6;

for $*ARGFILES.handles -> $IO {
    $IO.path.say
}

Ok so that's a bit more convoluted than looking at @*ARGS. But what if you wanted to print the first 5 lines for each file?

#! /usr/bin/env perl6
use v6;

for $*ARGFILES.handles -> $IO {
    say $IO.lines: 5;
}

Or maybe you just want to read the contents of all the files and print them out?

#! /usr/bin/env perl6
use v6;

.say for $*ARGFILES.lines;

Hope that gives you some ideas.

Upvotes: 6

Kingsley
Kingsley

Reputation: 14906

For Perl6 the arguments array is @*ARGS, this gives the code:

#! /usr/bin/env perl6

use v6;

for @*ARGS -> $arg
{
    print("Arg $arg\n");
}  

So you just need to remove the .perl from your my @args = @*ARGS.perl; line.

EDIT: Updated as per Ralphs's comments

Upvotes: 10

Related Questions