Perl code to read one line from a text file

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 line 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 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 Perl subroutine opens the file, gets the record, and returns the record from the file. Here’s the 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";

As a quick summary, if you need an example of how to read one line from a text file in Perl, I hope this example is helpful.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.