doubledecker has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I'm trying to figure out what exactly is the problem with my code. am trying to open a file, print and close it using the module FileHandle. But I'm encountering the following error

Can't call method "close" on an undefined value at ...... line ......

Here is the code snippet

use strict; use FileHandle; my $LOG = "/tmp/log.txt"; my $fh = FileHandle->new(">> $LOG"); print $fh "this is a test"; $fh->close;

Replies are listed 'Best First'.
Re: error using FileHandle Module
by cjb (Friar) on Dec 16, 2010 at 09:29 UTC

    You're assuming the new file handle has been created. Try adding a die to it.

    my $fh = FileHandle->new(">> $LOG") or die $!;

    What error does that give you?

      Minor nit:

      my $fh = FileHandle->new(">> $LOG") or die "$! opening '$LOG'";

        I tried my own code on different directory say '/tmp'. Problem is with I don't have proper permissions to create the LOG from the Perl script.

        Thanks for all the efforts

Re: error using FileHandle Module
by Anonymous Monk on Dec 16, 2010 at 07:24 UTC
    The SYNOPSIS for FileHandle shows
    $fh = FileHandle->new("> FOO"); if (defined $fh) { print $fh "bar\n"; $fh->close; }
    Try that.
      Try This one. This will work. use strict; use FileHandle; my $LOG = "log.txt"; my $fh = FileHandle->new(">> $LOG"); if (defined $fh) { print $fh "bar\n"; $fh->close; }
Re: error using FileHandle Module
by Khen1950fx (Canon) on Dec 16, 2010 at 09:28 UTC
    I couldn't replicate your error, so I put your script together with anonimonk's script---both work for me.
    #!/usr/bin/perl use strict; use warnings; use FileHandle; my $log = '/root/Desktop/log.txt'; my $fh1 = FileHandle->new("> $log") or die $!; print $fh1 "this is a test\n"; $fh1->close; my $fh2 = FileHandle->new(">> $log") or die $!; if (defined $fh2) { print $fh2 "bar"; $fh2->close; }