Perl code example: process command line argument with options

Here is a beautiful Perl code example that process command line arguments with specified options. With this code snippet, you can define any number of options like a professional Perl developer in a professional way. It is pretty because it is the most precise way to specify options for command line arguments I have ever seen.

It allows us to use the following format of usage:

perl process.pl -l java -t testset1

All the command-line arguments are read to @ARGV array, and that is the start of this command line argument processing example.

# file name: process.pl
while (scalar @ARGV > 0){
	$Temp = shift @ARGV;
	if ($Temp eq '-l'){
		$NextParam = 'language';
	}
	elsif ($Temp eq '-t'){
		$NextParam = 'test';
	}
	elsif (defined $NextParam){
		if ($NextParam eq 'language'){
			$Lang = $Temp;
		}
		elsif ($NextParam eq 'test'){
			$Test = $Temp;
		}
 
		undef $NextParam;
	}
}

This approach can be applied to Java command line argument processing even though we don’t use command line often in Java.

Note: Since $ARGV[0] is the first argument, $#ARGV is the number of arguments minus one.

Leave a Comment