Perl code to read one line from a text file

By Alvin Alexander. Last updated: Aug 6, 2011

When I work with Perl I'm often performing a task where I need to read from a text file, and many times all I have to do is read one record from the file. This happened again today, where I have a text file that just contains one pid (process id), and I just need to get that pid right before I do some other work.

Today I wrote a little subroutine named get_record to handle this function for me. I just pass in the name of the file I want to read from, and the subroutine opens the file, gets the record, and returns the record from the file. Here's my free source code for this example:

sub get_record
{
# the filename should be passed in as a parameter
my $filename = shift;
open FILE, $filename or die "Could not read from $filename, program halting.";
# read the record, and chomp off the newline
chomp(my $record = <FILE>);
close FILE;
return $record;
}
# a test to show how to call my function
$text = &get_record('pid.dat');
print "text = $text\n";