next up previous contents index
Next: File Handles Up: Input/Output Previous: Standard Input/Output/Error   Contents   Index


Command line arguments

The use of STDIN is one way to get information interactively from a user. For some purposes though the use of command-line arguments may be more convenient. What happens here is that a user runs the script with certain arguments after the script name:
  perl my_script.pl 34 66 dallas
and the arguments 34, 66, and dallas are captured and subsequently used in your program. How this can be done with Perl is through the use of a special array called @ARGV which Perl will create when the script is run; the elements of @ARGV are the command-line arguments used (if any) when the script was invoked. For example, if we had a script
  for my $arg (@ARGV) {
    print qq{You passed in $arg\n};
  }
and ran it as perl my_script.pl 34 66 dallas, then we would find as output
  You passed in 34
  You passed in 66
  You passed in dallas
Using command-line arguments is often convenient for passing in oft-used information and in which printing out a message and then waiting for user input can be tedious. See the documentation for the Getopt::Std and Getpt::Long modules for a more flexible approach for command line processing.

The print LIST function is used for relatively straightforward items. At times though you may want to do some formatting of the results. For this purpose you can use the printf function:

my $pi = 3.1415926539052;
printf( qq{Pi to 5 decimal places is %.5f}, $pi);
You can put in multiple format statements, in which case the variables will be formatted in order:
my $n = 5;
my $pi = 3.1415926539052;
printf( qq{Pi to %d decimal places is %.5f}, $n, $pi);
The % symbol is used to signal the type of format to use - some common ones are By appending .d (where d is a number) after %f or or %e you can specify the number of digits after the decimal place to print. You can also do some justification of how the results appear on the screen by using a number before the format character:
printf( qq{<%10d>\n}, 12);
will print out
<        12>
while
printf( qq{<%-10d>\n}, 12);
will print out
<12        >

There is also a sprintf function, used as, for example

my $pi = 3.1415926539052;
my $truncated_pi = sprintf( qq{\%.5f}, $pi);
to assign a formatted expression to a variable.
next up previous contents index
Next: File Handles Up: Input/Output Previous: Standard Input/Output/Error   Contents   Index