NirMH
NirMH

Reputation: 4929

is it possible to copy a file handle to another variable?

I have a very straitforward question i couldn't find an answer for it.

Say we have a section of code that performs a common task (e.g., a sub), and the output of that code should be directed to a specific file handle based on some criteria.

Is it possible to copy the target file handle to a local variable? if yes how?

e.g.,

my $key;
my $tempFh;
my $targetFh1 = open (...);
my $targetFh2 = open (...);

if ($key eq "1")
{
   $tempFh = $targetFh1;
}
else
{
   $tempFh = $targetFh2;
}

#perform the common activity
print $tempFh "common activity\n";

Upvotes: 1

Views: 579

Answers (2)

ikegami
ikegami

Reputation: 385915

Yes.

The only issue is the syntax of open.

my $targetFh1 = open (...);
my $targetFh2 = open (...);

should be

open(my $targetFh1, ...) or die $!;
open(my $targetFh2, ...) or die $!;

The rest is fine.

my $fh;
if ($key eq '1') {
   $fh = $targetFh1;
} else {
   $fh = $targetFh2;
}

print $fh "common activity\n";

(The word temp is completely meaningless, so I removed it.)

Another syntax you could use is

my $fh = $key eq '1' ? $targetFh1 : $targetFh2;
print $fh "common activity\n";

Or even

print { $key eq '1' ? $targetFh1 : $targetFh2 } "common activity\n";

But unless the print is in a loop and $key can change from loop pass to loop pass, there's no reason to open both files like that. You could simply use

my $fh;
if ($key eq '1') {
   open($fh, ...) or die $!;
} else {
   open($fh, ...) or die $!;
}

print $fh "common activity\n";

Upvotes: 1

Sobrique
Sobrique

Reputation: 53488

Yes.

Use 3 arg open with a lexical filehandle:

open ( my $output_fh, ">", $output_filename ) or die $!;

Assign the filehandle:

my $temp_fh_ref = $output_fh;
print {$temp_fh_ref} "Some text"; 

Works exactly like you'd expect. (Just bear in mind that if you close one, you'll close both)

Upvotes: 0

Related Questions