Lesson 19: Sanity checks and testing


It is always important to test user input.

  1. Checking that user input has indeed been supplied
  2. Verifying that a file really exists

Testing

test description
defined checks if a variable is defined
file test: -e checks if a file exists
file test: -s returns the size of the file

Dealing with incorrect data

action description
die prints a message to STDERR and kills the program
warn prints a message to STDERR

Testing for user input

Command-line:

%% ./user_input.pl one

Code: Checks to see if an argument was provided, and if it is then the argument will be assigned to $in_1. Otherwise the 'if statement' will be executed and the script will die and an error message will be printed.

1
2
3
4
5
6
7
my $in_1;
 
if (!defined $ARGV[0]){
  die "Please supply a number\n";
}else{
  $in_1 = $ARGV[0];
}

file tests

Command-line:

%% ./user_input.pl file.txt

Code: the checks are the same as above, but with an added file test. -e tests that a file exists

1
2
3
4
5
6
7
8
9
10
my $filename;
 
if (!defined $ARGV[0]){
  die "Please supply a file\n";
}elsif (!-e $ARGV[0]){
  die "$ARGV[0] does not exists.
       Please check the filename and/or location.\n";
}else{
  $filename = $ARGV[0];
}

Exercises

  1. Modify the script that takes 2 numbers from the command line
  2. Add a check to be sure that 2 arguments are supplied. Die if there are too few arguments
  3. Add the two numbers and print the result

Print Friendly

Leave a Reply

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