Lesson 18: User/Command-line input


How do you get arguments from the user into your script?

  • Incorporating input from the command-line
  • Perl creates an array, @ARGV, which contains the contents of the command-line following the script name

@ARGV
Command-line:

%% ./user_input.pl one two three

Code:

1
2
my @user_input = @ARGV;
print join ("\n" , @user_input) , "\n";

Output:

%% ./user_input.pl one two three
one
two
three

shift and @ARGV

  • Remember the array function shift removes and returns the first element of an array.

Command-line:

%% ./user_input.pl one two three

Code:

1
2
my $first_input = shift @ARGV;
print "first input: $first_input\n";

Output:

%% ./user_input.pl one two three
first input: one

Using array indices

  • Remember with arrays that each element can be accessed using indices.

Command-line:

%% ./user_input.pl one two three

Code:

1
2
3
my $first_input = $ARGV[0];
my $second_input = $ARGV[1];
print "$first_input and $second_input\n";

Output:

%% ./user_input.pl one two three
one and two

Assigning an array to a list of variables

Command-line:

%% ./user_input.pl one two three

Code:

1
2
my ($in_1, $in_2 , $in_3) = @ARGV;
print "$in_1 and $in_2 and $in_3\n";

Output:

%% ./user_input.pl one two three
one and two and three

Exercises

  1. Write a script that takes 2 numbers from the command line
  2. Add the two numbers and print the result

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *