Mon, 20 Oct 2008

The MAIN sub

Permanent link


"Perl 5 to 6" Lesson 14 - The MAIN sub


  # file

  sub MAIN($path, :$force, :$recursive, :$home = '~/') {
      # do stuff here

  # command line
  $ ./ --force --home=/home/someoneelse file_to_process


Calling subs and running a typical Unix program from the command line is visually very similar: you can have positional, optional and named arguments.

You can benefit from it, because Perl 6 can process the command line for you, and turn it into a sub call. Your script is normally executed (at which time it can munge the command line arguments stored in @*ARGS), and then the sub MAIN is called, if it exists.

If the sub can't be called because the command line arguments don't match the formal parameters of the MAIN sub, an automatically generated usage message is printed.

Command line options map to subroutine arguments like this:

  -name                   :name
  -name=value             :name<value>

  # remember, <...> is like qw(...)
  --hackers=Larry,Damian  :hackers<Larry Damian>  

  --good_language         :good_language
  --good_lang=Perl        :good_lang<Perl>
  --bad_lang PHP          :bad_lang<PHP>

  +stuff                  :!stuff
  +stuff=healthy                                        :stuff<healthy> but False

The $x = $obj but False means that $x is a copy of $obj, but gives Bool::False in boolean context.

So for simple (and some not quite simple) cases you don't need an external command line processor, but you can just use sub MAIN for that.


The motivation behind this should be quite obvious: it makes simple things easier, similar things similar, and in many cases reduces command line processing to a single line of code: the signature of MAIN.

SEE ALSO contains the specification.

[/perl-5-to-6] Permanent link

Comments / Trackbacks:

Trackback URL: /blog-en.trackback

Write a comment

URL: [] (optional)
Title: (optional)
Save my Name and URL/Email for next time