Using “-s” option to process arguments in perl

When writing simple scripts that need to process command line arguments, you'll find that perl has a neat little trick up it's sleeve that is not often used. but provides a nice shortcut to command line option handling.

To demonstrate this little gem, let's imagine a script that displays a specified string a specified number of times with a specified delimiter, and further imagine that you want to be able to invoke your script like this..

repeat.pl -str="hello" -count=10 -delim=","

The following code will do this..

#! /usr/bin/perl -s
our $str, $count, $delim;
print join($delim, ($str) x $count)."\n";

The trick we have made use of here is that the "-s" command line flag we specified on the #! line causes perl to take any options on the command line with the syntax "-varname=value" and pre-populates variables of the same name before executing the script.

If you specify the option without a value, then the value 1 is assumed.

Here's an example of the script being executed..

# repeat.pl -str="hello" -count=10 -delim="|"
hello|hello|hello|hello|hello|hello|hello|hello|hello|hello

You could also have called it using the command line..

perl -s repeat.pl -str="hello" -count=10 -delim="|"
Scroll to Top