adamcrussell

Using -s with Perl One Liners

For Perl Weekly Challenge 072 we are asked the following:

You are given a text file name $file and range $A -  $B where $A <= $B. Write a script to display lines range $A and $B in the given file.

I was a bit surprised to realize how this could be done with a one liner. In the example below input.txt is a plain text file which has 100 lines that all look like LX for 1 <= X <= 100.

$ perl -s -n -e 'print if $. >= $A && $. <= $B' — -A=4 -B=12 < input.txt

L4
L5
L6
L7
L8
L9
L10
L11
L12

The use of the special variable $. to track input line numbers is a common Perl idiom. What was surprising to me was that I was unfamiliar with the -s command line option. This option allows you to set variables on the command line. Anything after the is interpreted to be a variable initialized to the given value. You can see that in the example above where -A=4 and -B=12 creates variables $A and $B initialized to 4 and 12 respectively. 

If you do not set the variable to something then it is just initialized as true. For example:

$ perl -s -e 'print "$x\n";' — -x
1


Comments for this post were locked by the author