Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I use a class property/variable as a print filehandle in Perl?

I want to do the same thing as

open MYFILE, ">", "data.txt";
print MYFILE "Bob\n";

but instead in class variable like

sub _init_tmp_db
{
    my ($self) = @_;

    open $$self{tmp_db_fh}, ">", "data.txt";
    print $$self{tmp_db_fh} "Bob\n";
}

It gave me this error : 'String found where operator expected near "Bob\n"'

what should I do?

like image 547
Jessada Thutkawkorapin Avatar asked Jan 30 '12 14:01

Jessada Thutkawkorapin


2 Answers

From the print manpage:

If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead.

You should be using:

print { $$self{tmp_db_fh} } "Bob\n";

This code won't work under use strict. To fix it just use a my variable:

open my $fh, ">", "data.txt" or die $!;
$$self{tmp_db_fh} = $fh;
print { $$self{tmp_db_fh} } "Bob\n";
like image 69
Eugene Yarmash Avatar answered Nov 27 '22 19:11

Eugene Yarmash


You should the IO::File module instead.

use IO::File;
my $file = IO::File->new;
$file->open("> data.txt");

print_something($file);

sub print_something {
  my ($file) = @_;
  $file->print("hello world\n");
} 

Or in your example function:

use IO::File;
# ...
sub _init_tmp_db
{
    my ($self) = @_;

    $self{tmp_db_fh} = IO::File->new;
    $self{tmp_db_fh}->open(">", "data.txt");
    $self{tmp_db_fh}->print"Bob\n";
}

(note, you can still non -> based calls too, but I wrote the above using the more traditional ->open() type calls.)

like image 32
Wes Hardaker Avatar answered Nov 27 '22 19:11

Wes Hardaker