Home » Perl Basics » 09 - Input / Output
9

Reading from a pipe

What does 'reading from a pipe' mean?

Perl can read from a variety of sources. Files being one, return from shelf command or directory are other options. You may want to execute a shell command and analyze the return of that command with Perl.
Until now the only you could have used it redirect the shell command into a file and run your Perl script on that file. But Perl can run shell command in the script.

  #!/usr/bin/perl 
  #author : you
  #date : 5.10.2007
  #purpose : File I/O shell command analyze 
  open (FILEHANDLE, “ls –la | grep data”) || die “error $!”;
  @ls-la = <FILEHANDLE>;
  foreach (@ls-la) { print “$_”;}
  #END
  
This script will print all the file on the directory the script is that contain the string “data”.
Reading a directory could be done with the function above but Perl has special function to open and read directories.

  #!/usr/bin/perl 
  #author : you
  #date : 5.10.2007
  #purpose : File I/O open directory
  $directory-to-list = “/the/directory/you/want/to/list”; 
  Opendir (HANDLE, “$directory-to-list”) || die “error $!”;
  @list-of-the-directory = readdir(HANDLE);
  foreach (@list-of-the-directory) { print “$_ \n”;}
  #END
  
The opendir function is similar to the open function in every way. However you cannot read the content as is. In order to list the content you need to use the “readdir” function and redirect the output to an array in order to access the data. Notice that we dir add the “\n” at the end of each loop as the output of the array created from “readdir” would be on one line only if we didn’t. Also the readdir function will give you the content of the directory and nothing else, a simple list of file without any specific information about those files.
A question you might be asking yourself right now is why use opendir and readdir if you can have better information with the first method?
The first method is system specific . If you use it in windows it will simply return an error. Using readdir and opendir will allow for a better portability of the script.