14. Special variable @ARGV
In Perl, you can access command-line parameters using the @ARGV array. This array contains the arguments passed to your Perl script when
it is executed. Here's a basic example of how to use @ARGV:
# Check if there are any command-line arguments. Notice that @ARGV is evaluated in scalar context, returning the number of arguments!
if (@ARGV) { # or if ( scalar(@ARGV) )
print "You provided the following command-line arguments:\n";
# Loop through the command-line arguments and print each one
foreach $arg (@ARGV) {
print "$arg\n";
}
}
else {
print "No command-line arguments provided.\n";
}
Save this code to a file (e.g., script.pl) and make it executable (e.g., chmod +x script.pl).
You can then run it from the command line with various arguments:
./script.pl arg1 arg2 arg3
In this example, @ARGV will contain ("arg1", "arg2", "arg3"), and the script will print each argument one by one.
You can access and manipulate the command-line arguments as needed for your script's functionality.
14.1 Validate input.
To check if the arguments are e.g. positive integers, you could write:
if(@ARGV) {
for(@ARGV){
die "Expected only positive integers: $_" unless /^\d+$/;
}
}
else {
print "No command-line arguments provided.\n";
}
14.2 Example
An easy example of converting a string of alphabetic characters into a number. The number is calculated by adding the numeric alphabetic position of the characters.
Example: abc = 6 (1+2+3). New is the use of a hash, which is the subject of Part 2.
%alphabet = (
'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7,
'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14,
'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21,
'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26,
);
if (@ARGV) {
for (@ARGV) {
die "Expected only alphabetic characters: $_" unless /^[a-zA-Z]+$/;
}
foreach $arg (@ARGV) {
$sum = 0;
@chars = split(//,uc($arg));
foreach $char (@chars) {
$sum = $sum + int($alphabet{$char});
}
print "$arg: $sum\n";
}
}
else {
print "Error: No command-line arguments provided.\n";
}