Q:

grab nth line in perl where n can be four integers

I would like to take four lines from a file using Perl. I have four integer variables; for instance:
a= 5;
b = 45;
c=30;
d=8;

Is it possible to grab and store as four strings the line numbers from a file that correspond to these values (i.e. line 5, line 45, line 30, line 8)? I have been playing around with
-ne 'print if($.==5)';

But is there a more eloquent way? This just seems to check for what line I am currently on...

A:

If you want it as a one-liner, using a hash makes it pretty easy:
perl -ne '%lines = map { $_ => 1 } 23, 45, 78, 3; print if exists $lines{$.}' test.txt 

This creates a hash that looks like ( 23 => 1, 45 => 1, 78 => 1, 3 => 1 ) and then uses exists to check if the current line number is a key in the hash.

A:

If you're working with a small file and have the memory to slurp the contents into the script, you could slurp the file into an array and then access the lines as array elements:
# define the lines you want to capture
$a=5;
$b=45;
$c=30;
$d=8;

# slurp the file into an array
@file = <>;

# push the contents of the array back by one
# so that the line numbers are what you expect
# (otherwise you would have to add 1 to get the
# line you are looking for)
unshift (@file, "");

# access the desired lines directly as array elements
print $file[$a];
print $file[$b];
print $file[$c];
print $file[$d];

If you're looking for command line one-liners, you could also try awk or sed:
awk 'NR==5' file.txt
sed -n '5p' file.txt

