- Perl ›
- Predefined variable ›
- here
Handling Command Line Arguments @ARGV
Learn how to handle command line arguments in Perl.
Command line arguments are arguments that can be specified after the program name, separated by spaces.
For example, if you want to specify the values "1", "3", and "5" when executing "test.pl", you can call the program as follows.
perl test.pl 1 3 5
The above example is a number, but a string such as a file name is also acceptable.
perl test.pl a.txt b.txt
Useing Whitespace in Command Line Arguments
The command line argument delimiter is blank. If you want to use whitespace, you need to escape it with double quotes.
perl test.pl foo "bar baz"
Receiving Command Line Arguments
The command line arguments are assigned to the @ARGV Predefined Variables. This predefined variable can be used in the same way as a normal Arrays.
For example, if multiple numbers are specified as command line arguments, assign them to the named array.
my @nums = @ARGV;
You can also use List Assignment to receive command line arguments.
my ($name, $age) = @ARGV;
You can use The shift Function with no arguments to receive the first argument of @ARGV.
# Get the first value of @ARGV my $file = shift;
In either case, do not use "@ARGV" as it is, but store it in the named Variables.
If you want to know the number of command line arguments, @ARGV is a normal variable, so you can get it by evaluating it with Scalar Context.
# Number of command line arguments my $count = @ARGV;
The arguments in Subroutines were assigned to a predefined variable called @_ . The command line arguments are @ARGV , so be sure to distinguish them and remember them.
Handle command line argument "options"
If you want to handle "optional" form of command line arguments in addition to the usual command line arguments, it's easy to use a module called Getopt::Long.