Perl - How to read from a named pipe (fifo)

Perl FAQ: How can I write a Perl script to read from a named pipe (FIFO file)?

Here’s some code from a Perl program where I open up a named pipe (a FIFO file), then read data from that file until the end of time ... or at least until someone kills this program.

my $fifo_file = "/opt/devdaily/ftpapp/ftp.fifo";

my $fifo_fh;
open($fifo_fh, "+< $fifo_file") or die "The FIFO file \"$fifo_file\" is missing, and this program can't run without it.";

# just keep reading from the fifo and processing the events we read
while (<$fifo_fh>)
{
  &handle_fifo_record($_);
}

# should never really come down here ...
close $fifo_fh;
exit(0);

As you can see there’s not too much to this. Just open the FIFO file like a regular file, then keep reading the data that is passed into the other end of the pipe.

In my case the data records look something like this:

field1 | field2 | field3 | field4 | field5

so all I have to do is process each one of these records, one at a time, inside my program.

If you thought it might be hard to read from a named pipe in Perl, I hope this demonstrates that it’s not hard at all.