home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

6.3. The Invocation Arguments

Technically, the diamond operator isn't looking literally at the invocation arguments -- it works from the @ARGV array. This array is a special array that is preset by the Perl interpreter to be a list of the invocation arguments. In other words, this is just like any other array, (except for its funny, all-caps name), but when your program starts, @ARGV is already stuffed full of the list of invocation arguments.[150]

[150]C programmers may be wondering about argc (there isn't one in Perl), and what happened to the program's own name (that's found in Perl's special variable $0, not @ARGV). Also, depending upon how you've invoked your program, there may be a little more happening than we say here. See the perlrun manpage for the full details.

You can use @ARGV just like any other array; you could shift items off of it, perhaps, or use foreach to iterate over it. You could even check to see if any arguments start with a hyphen, so that you could process them as invocation options (like Perl does with its own -w option).[151]

[151]If you need more than just one or two such options, you should almost certainly use a module to process them in a standard way. See the documentation for the Getopt::Long and Getopt::Std modules, which are part of the standard distribution.

This is how the diamond operator knows what filenames it should use: it looks in @ARGV. If it finds an empty list, it uses the standard input stream; otherwise it uses the list of files that it finds. This means that after your program starts and before you start using the diamond, you've got a chance to tinker with @ARGV. For example, here we can process three specific files, regardless of what the user chose on the command line:

@ARGV = qw# larry moe curly #;  # force these three files to be read
while (<>) {
  chomp;
  print "It was $_ that I saw in some stooge-like file!\n";
}

In Chapter 11, "Filehandles and File Tests", we'll see how to open and close specific filenames at specific times. But this technique will suffice for the next few chapters.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.