How to save and access a file descriptor in a Perl class?

check out the following code first.

#! /usr/bin/perl package foo; sub new { my $pkg = shift; my $self = {}; my $self->{_fd} = undef; bless $self, $pkg; return $self; } sub Setfd { my $self = shift; my $fd = shift; $self_->{_fd} = $fd; } sub write { my $self = shift; print $self->{_fd} "hello word"; } my $foo = new foo; 

My intention is to store the file descriptor inside the class using a hash. the file descriptor is undefined first, but it can be initialized by calling the Setfd function. then write can be called to actually write the string "hello word" to the file specified by the file descriptor, assuming that the file descriptor is the result of a successful "write".

but the perl compiler just complains about a syntax error in the "print" line. can any of you tell me what is wrong here? thanks in advance.

+7
perl filehandle
source share
2 answers

You will need to put the expression $self->{_fd} in the block or assign it to a simpler expression:

  print { $self->{_fd} } "hello word"; my $fd = $self->{_fd}; print $fd "hello word"; 

From perldoc -f print :

Please note: if you store FILEHANDLE in an array or use another expression that is more complicated than a scalar variable, to get it, you will need to use a block that returns the file descriptor value:

 print { $files[$i] } "stuff\n"; print { $OK ? STDOUT : STDERR } "stuff\n"; 
+14
source share

As an alternative:

 use IO::Handle; # ... later ... $self->{_fd}->print('hello world'); 
+6
source share

All Articles