Home » Perl Basics
7

Parameters

Learn how to pass arguments and execute Perl values.

Perl also allows you to pass arguments when you execute it.

  #> ./perl_script.pl argument1 argument2 ..etc…
Those arguments are stored in an array type variable that Perl keeps. This array is @ARGV (case sensitive).
That array can be used like any other array in the script . To call a single value
  $ARGV[0]
To call multiple values
  @ARGV[0..2]
You will want some scripts to only take a certain number of arguments. With Perl you can easily make a condition that will stop stop the script if the expected number of argument is not right.
  Unless  ($#ARGV == 2) {     So the total number of argument is 3 since $#ARGV begins at 0
  print “the script will stop”;
  }
Remember that $#ARGV return the number of the last element of a list so the total number of element is $#ARGV + 1.
You can increment the value of $#ARGV in the script by using
  $#ARGV +=1;
When you do more complex scripts you may want to know why the script fails. In order to do that you may want to use the function “exit”
The function exit on top of exiting the script will also return whatever error code you want. Simply define a scalar type variable with an error code and and use the exit function like so:
Exit $name-of-your-variable.
Using exit is especially interesting when the script user is not the script writer or/and the scipt user does not have the expertise to deduct what kind of error is return. To return the error code in the shell