File closure problems

Discussion in 'Perl Misc' started by Jonas Andersson, Nov 1, 2004.

  1. Hi,

    I sometimes get weird problems with file closures in Perl:

    print FILE "...a lot of data...";
    close(FILE) or &error_catcher;

    sub error_catcher {
    print "Error around line $line_number. Exiting. \n";

    Any idea why this happens? I thought Perl waited for the writing to
    the file to finish before it tried to close it? What could I do in
    this situation?

    Thanks for your time,

    Jonas Andersson, Nov 1, 2004
    1. Advertisements

  2. Also sprach Jonas Andersson:
    Note that using 'closure' in this context is a bit misleading. It's
    usually used to refer to a different concept (that of functions or
    function-references having access to outside variables).
    Perl just writes to a filehandle. The operating system does the work
    behind the curtains. There is usually little need to wait (not in the
    case of regular files certainly).

    Have you considered checking why it failed? Your operating system knows
    much better than people in this group:

    sub error_catcher {
    print "Error...: $!";
    exit 1;

    The value of $! plus the first paragraph of 'perldoc -f close' should
    give you a pretty accurate idea what went wrong.

    A minor nit: When your program exits due to an error, you should
    indicate that by providing an exit code other than zero. It's a question
    of good style and following the conventions nicely.

    Tassilo v. Parseval, Nov 1, 2004
    1. Advertisements

  3. "Weird problems"? I left my ESP helmet at home today; I have
    no idea what "weird problems" might refer to.
    Don't use & on subroutine calls unless you know what it does
    and you want that behavior. The builtin function die does
    what you're doing here except it does it much better; see
    Why what happens? "Weird problems" is not an error description.

    Incidentally, your code is poor. Better:

    close (FILE) or die "Error closing file:$!";

    By not finishing the string you give die with a newline, it
    will automatically report the line you died on. $! will
    report what error close() actually gave.
    Christopher Mattern

    "Which one you figure tracked us?"
    "The ugly one, sir."
    "...Could you be more specific?"
    Chris Mattern, Nov 1, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.