WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Perl · Intermediate · question 23 of 100

Explain how to work with command-line arguments in Perl scripts.?

📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

In Perl, command-line arguments can be accessed from the special ‘@ARGV‘ array. The ‘@ARGV‘ array contains all the command-line arguments passed to the script on invocation, with the first argument at index 0, the second at index 1, and so on.

For example, the following code prints all the command-line arguments passed to the script:

#!/usr/bin/perl

foreach my $arg (@ARGV) {
   print "$argn";
}

If the script is called with the command ‘perl script.pl foo bar baz‘, the output would be:

foo
bar
baz

To access specific command-line arguments, you can simply index into the ‘@ARGV‘ array like any other array. For example, to print the second command-line argument, you would use:

#!/usr/bin/perl

print $ARGV[1], "n";

If the script is called with the command ‘perl script.pl foo bar baz‘, the output would be:

bar

Additionally, Perl provides a built-in special variable ‘$#ARGV‘ which contains the index of the last element in the ‘@ARGV‘ array.

Here’s an example script that parses command-line arguments with Getopt::Long:

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my $foo;
my $bar;
my $baz;

GetOptions(
    "foo=s" => $foo,
    "bar=i" => $bar,
    "baz"   => $baz,
);

print "foo: $foon" if defined $foo;
print "bar: $barn" if defined $bar;
print "baz: $bazn" if defined $baz;

The ‘GetOptions‘ function in the example above is used to parse command-line options using Getopt::Long. The ‘foo‘ and ‘bar‘ options expect an argument (‘s‘ for a string and ‘i‘ for an integer), while ‘baz‘ is used as a simple flag. The values of the command-line options are stored in the respective variables (‘$foo‘, ‘$bar‘, and ‘$baz‘) after parsing.

To call this script with options, you can use the following commands:

perl script.pl --foo=hello --bar=42 --baz

This would output:

foo: hello
bar: 42
baz: 1

Overall, working with command-line arguments in Perl is straightforward, with built-in support for accessing command-line arguments directly via ‘@ARGV‘, as well as the ability to easily parse command-line options using modules such as Getopt::Long.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Perl interview — then scores it.
📞 Practice Perl — free 15 min
📕 Buy this interview preparation book: 100 Perl questions & answers — PDF + EPUB for $5

All 100 Perl questions · All topics