How to eliminate a copy of the STDIN file descriptor?

I am trying to figure out how to get a Perl module to respect and open a link to a file descriptor. You will understand what I mean when you see the main program:

#!/usr/bin/perl use strict; use warnings; use lib '/usr/local/share/custom_pm'; use Read_FQ; # open the STDIN filehandle and make a copy of it for (safe handling) open(FILECOPY, "<&STDIN") or die "Couldn't duplicate STDIN: $!"; # filehandle ref my $FH_ref = \*FILECOPY; # pass a reference of the filehandle copy to the module subroutine # the value the perl module returns gets stored in $value my $value = {Read_FQ::read_fq($FH_ref)}; # do something with $value 

Basically, I want the main program to receive input via STDIN, create a copy of the STDIN file descriptor (for safe processing), then transfer the link to this copy to the read_fq () routine in the Read_FQ.pm file (perl module). Then the routine will read the input of this file descriptor, process it and return a value. Here is the Read_FQ.pm file:

 package Read_FQ; sub read_fq{ my ($filehandle) = @_; my contents = ''; open my $fh, '<', $filehandle or die "Too bad! Couldn't open $filehandle for read\n"; while (<$fh>) { # do something } close $fh; return $contents; 

Here where I run into problems. In terminal, when I pass the file name to the main program to open:

cat file.txt | ./script01.pl

The following error message appears: Too bad! Couldn't open GLOB(0xfa97f0) for read Too bad! Couldn't open GLOB(0xfa97f0) for read

This tells me that the problem is how I dereference and open the link to the file descriptor in the perl module. The main program is in order. I read that $refGlob = \*FILE; is a reference to a file descriptor and in most cases, you should automatically dereference Perl. However, this is not the case. Does anyone know how to dereference a file descriptor so that I can process it?

thanks. Any suggestions are welcome.

+7
source share
2 answers

Your $filehandle should already be open - you opened FILECOPY , took the link and placed it in $FH_ref , which is equal to $filehandle . If you want to open it again, use the <& argument in open or start reading it right away.

+4
source

If I understand correctly, you need an equivalent

 open my $fh, '<&STDIN' 

This will

 open my $fh, '<&', $filehandle 

I don’t know why you want it.

+2
source

All Articles