Categories

Posts in this category

Wed, 19 May 2010

This Week's Contribution to Perl 6 Week 3: Write supporting code for the MAIN sub


Permanent link

For this week's contribution to Perl 6 we ask you to write some Perl 6 code that parses command line arguments, and might end up in the code base of a Perl 6 compilers.

(Introduction to this series of challenges)

Background

In Perl 6 you can write a sub MAIN that is automatically called when the script is run, and it handles command line parsing for you.

So for example if you write

sub MAIN($filename, *@rest, :$verbose) {
    ...
}

And you call the script as

perl6 create_many_copies.pl --verbose=2  /etc/password pw1 pw2 pw3

The parameters are automatically set to $filename = '/etc/password', @rest = ('pw1', 'pw2', 'pw3') and $verbose = 2.

What you can do

Write a subroutine in Perl 6 that takes an array of command line arguments, and a hash of option names that are declared as Bool, and returns an array of positional arguments, and a hash of named arguments

sub process-cmd-args(@args, %boolean-names) {
    ...
    return @positional-arguments, %named-arguments;
}

It should separate the named arguments (options) and the ordinary, positional arguments. For example a command line argument of --myname=23 should be result in a hash entry %named-arguments{'myname'} = 23. If a named option is declared as type Bool, then --myoption foo is turned into %named-arguments{'myoption'} = True, @positional-arguments = 'foo'. Otherwise it is taken as %named-arguments{'myoption'} = 'foo'.

The specification describes the various syntax forms in detail, but you are very welcome to implement only parts of them. For example it's recommended to ignore the negation forms, short names and spaces inside options.

We will then use the separate positional and named arguments to call the MAIN routine.

If you need some more background on how to write Perl 6 code, I recommend to start with a book that is currently being written (you can find a fairly up-to-date PDF version here.). See also our documentation overview.

Submission

Your program should run with the current Rakudo Perl 6 compiler - bonus points if you also provide some tests.

Please send your submission to the perl6-compiler@perl.org mailing list, and set me (moritz.lenz@gmail.com) as CC, because the mailing list sometimes has a large delay.

Update:: patrickas has submitted one implementation to this github repository. Instead of starting your own implementation, you can also contribute to this one (ask on #perl6 for commit access), and of course you're still eligible for winning a cool Perl 6 or Rakudo t-shirt.

If you have any questions, please ask the mailing list, me or (preferred) on our IRC channel, #perl6.

I will try to integrate the best submission into Rakudo (though it might not happen before the upcoming release on Tuesday).

[/perl-6] Permanent link