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

Hi Monks, Most documents refer to using a global variable for a filehandle, e.g. I have seen references to using
$sym = gensym; open($sym, "filename");
Are there any caveats with using a lexically scoped variable as a filehandle, provided that one plans to open AND close the file within that scope?
Example program:
#!/usr/bin/perl -w use strict; sub writelog{ my ($file,@text) = @_; my $fh; open($fh,">>",$file) || return undef; print $fh "--- ",time," ---\n"; print $fh "$_\n" foreach (@text); close($fh); return 1; } writelog("logfile","using lexically scoped var");

Replies are listed 'Best First'.
Re: using lexically scoped variable as a filehandle
by friedo (Prior) on Feb 21, 2007 at 13:33 UTC

    That will work fine -- although it's a little prettier to say open my $fh, '>>', $file; instead of doing it in two lines.

    When a lexical filehandle is garbage-collected (at the end of its scope) it will automatically be closed. So if you want, you can omit the close statement. On the other hand, explicit code never hurt anyone. :)

      Can you think of circumstances in which close will fail? I do :-)

      If you say

      open my $fh, '>>', $file or die $!;

      you should also say

      close $fh or die $!;

      when done, IMHO.

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
        Can you think of circumstances in which close will fail? I do :-)

        If you say open my $fh, '>>', $file or die $!; you should also say close $fh or die $!; when done, IMHO

        I'm gonna call you on this. Not because you are wrong, but because I haven't made up my about it mind yet.

        Let's consider both scenarios when the close fails:

        1. The open append may fail for a variety of reasons. Existance, permissions, in-use etc.

          Dying at this point in the proceedings may waste whatever work was done till now, but the (this) output file hasn't been touched, so recovery probably consists of correcting whatever caused the failure and re-running the program.

        2. For the close to fail, it basically come down to one reason, thought here could be several underlying causes, that some amount of written & cached, but unflushed output, could not be flushed to disk.

          Recovery is all together more complicated. The file has almost certainly been modified, but not in a consistant manner, so the error definitely needs to be recorded. Unless the application makes provision to record the file length prior to writing to the file, there is no possibility of automated recovery, as there is no way to determine how much was not flushed.

          But dying at this point achieves nothing accept to ensure that all subsequent processing is aborted, which will often compound the problem--by leaving other persistance state in a indeterminate place--rather than alleviating it. </lo>

        So, IMO, you almost never want to die on close failure, warn maybe, but not die.

        Update: I also question the likelyhood of close actually failing, but that's probably a different discussion.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
        agreed, shmem, i wish more people would follow that advice. even though 99% of the time close() will not fail, it's always that 1% that ends up biting you in the ass :o

        __________
        Systems development is like banging your head against a wall...
        It's usually very painful, but if you're persistent, you'll get through it.

Re: using lexically scoped variable as a filehandle
by shmem (Chancellor) on Feb 21, 2007 at 13:35 UTC
    That's perfectly fine, as long as you don't use write, which requires filehandles (and formats) to be global, i.e they must be in the symbol table.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      Thanks all for the reassuring responses although I'm intrigued by the limitations on using non-global handles with the write function.
      Since this type of code will go into a modperl environment (so the 'program' will never really terminate) it is important to be 100% sure the system will indeed close a file and free the associated resources.

      They do have to be in the symbol table, but they don't have to be globals. I won't say more, however, because it's probably better to encourage novices to use something like Perl6::Form instead.

Re: using lexically scoped variable as a filehandle
by ambrus (Abbot) on Feb 21, 2007 at 13:53 UTC
    $sym = gensym; open($sym, "filename");

    If you see code like that, I think it was for old versions of perl (I belive pre-5.6) where filehandles couldn't be autovivified, so you had to create a glob with gensym or open would complain.