aman
aman

Reputation: 375

Using a separate file handle to read a temporary file created using File::Temp

I created a temporary file using File::Temp and added some data to it. At some other point of time, I would like to read the temporary file, using a separate file handle (seek method works). Following is the code snippet.

#!usr/local/bin/perl
use File::Temp qw(tempfile);

my ($fh, $filename) = tempfile( SUFFIX => '.txt' );
my $towrite = "XXXX\nYYYY\nZZZZ\n";

open ANOTHERFH, "<", $fh or die "Cannot open $FH\n";
while (<ANOTHERFH>) {
   print "ANOTHERFH: $_";
}
close ANOTHERFH;

However, I get an error stating "Can't open GLOB...." Any suggestions

Upvotes: 2

Views: 290

Answers (2)

Eugen Konkov
Eugen Konkov

Reputation: 25153

Use $filename instead of $fh:

open ANOTHERFH, "<", $filename   or die "Cannot open $filename\n";

Or use dup as @ikegami suggest

Upvotes: 1

ikegami
ikegami

Reputation: 385897

To clone ("dup") a system file handle, the syntax is

open(my $fh, '<&', $fh_to_dup)          # dups into a new fd

or

open($existing_fh, '<&=', $fh_to_dup)   # dupds into fd fileno($existing_fh)

so you want

open(my $ANOTHER_FH, "<&", $fh)         # Avoid needless use of globals!
   or die("Can't dup temp file: $!\n");

Upvotes: 1

Related Questions