Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store and access a filehandle in a Perl class?

please look at 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 a file handle within a class using hash. the file handle is undefined at first, but can be initilized afterwards by calling Setfd function. then write can be called to actually write string "hello word" to a file indicated by the file handle, supposed that the file handle is the result of a success "write" open.

but, perl compiler just complains that there are syntax error in the "print" line. can anyone of you tells me what's wrong here? thanks in advance.

like image 859
Haiyuan Zhang Avatar asked Jun 12 '10 05:06

Haiyuan Zhang


People also ask

How do I use FileHandle in Perl?

The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively. File Handling is usually done through the open function. Syntax: open(FileHandle, Mode, FileName);

What is a file handle used for in Perl?

A filehandle is an internal Perl structure that associates with a file name. Perl File handling is important as it is helpful in accessing file such as text files, log files or configuration files. Perl filehandles are capable of creating, reading, opening and closing a file.


2 Answers

You will need to put the $self->{_fd} expression in a 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:

Note that if you're storing FILEHANDLEs in an array, or if you're using any other expression more complex than a scalar variable to retrieve it, you will have to use a block returning the filehandle value instead:

print { $files[$i] } "stuff\n";
print { $OK ? STDOUT : STDERR } "stuff\n";
like image 183
mob Avatar answered Sep 23 '22 15:09

mob


Alternately:

use IO::Handle;

# ... later ...

$self->{_fd}->print('hello world');
like image 45
Sean Avatar answered Sep 24 '22 15:09

Sean