Writing and reading to pipes (Perl)

When writing Perl scripts to automate shell tasks, file handlers will be used for reading files, writing to files, executing commands, redirecting output, … But these handlers can only be opened in one direction if they are created with the standard Perl subroutine open.

In some cases it is actually required to create a two way communication with the file handler, for instance when creating a pipe. In a pipe, some information is written to the pipe (left side of the pipe) which is read and analyzed by the right side of the pipe. This right of the pipe, is then able to produce some output.
If it is required to catch that output, we will need to have two file handlers!

A core module called IPC::Open2 provides an open2 subroutine, which allows to create a read and write file handler.

In the following example, we will mimic the shell command cat file|file -rik -, without calling the cat command. Instead we will open the file in RAW mode using Perl and then use file handlers to feed it to the file command and afterwards read the output.

Output produced by script:


Comments

Writing and reading to pipes (Perl) — 1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *