in reply to Perl Style: About error messges opening files

My style highly depends on the intended users, and how often it will be used. If it's a program I distribute, or write for someone else to use, I use something like:
open my $fh => $file or die "Failed to open file '$file': $!\n";
If it's code I just write for myself, I use something like:
open my $fh => $file or die "open: $!\n";
or
open my $fh => $file or die "open '$file': $!\n";
depending on how many files the program opens.

If it's a 'write-today-discard-tomorrow' program, I use:

open my $fh => $file or die "$!\n";
or even
open my $fh => $file or die;
I use the latter style when writing on the command line too.

Note that (except in the last case) I include a trailing newline. Most of the time, I couldn't care less on which line of the program an error occurs, especially not when it's about opening files.

I've been writing some C lately, and I've started appreciating perror. Perhaps I should write a little module give similar functionality.

Abigail

Replies are listed 'Best First'.
Re: Re: Perl Style: About error messges opening files
by demerphq (Chancellor) on Apr 27, 2004 at 11:11 UTC

    I've been writing some C lately, and I've started appreciating perror. Perhaps I should write a little module give similar functionality.

    Hmm. A start would be to just tell those of us who have never heard of it a bit about it. :-) (Like me.)

    And I usually leave the die line numbering enabled in my scripts. Most of the time my scripts are running on cron jobs in the background and when files arent there its usually a serious matter and I want to be able to track it back from the line it died from. Since the error messages get logged automatically it doesnt much bother folks. When its user displayed ill often do something like

    die "File '$foo' doesnt seem to exist!\n" unless -e $foo; open my $foo_fh,"<"',$foo or die "<$!:$foo";

    So that the common case errors are trapped specifically and the general case stuff that probably indicate more serious things are trapped by the open.


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi


      A start would be to just tell those of us who have never heard of it a bit about it.
      PERROR(3) Library functions PERROR(3) NAME perror - print a system error message SYNOPSIS #include <stdio.h> void perror(const char *s); #include <errno.h> const char *sys_errlist[]; int sys_nerr; DESCRIPTION The routine perror() produces a message on the standard error output, describing the last error encountered during a call to a system or library function. First (if s is not NULL and *s is not NUL) the argument string s is printed, followed by a colon and a blank. Then the mes- sage and a new-line. To be of most use, the argument string should include the name of the function that incurred the error. The error number is taken from the external variable errno, which is set when errors occur but not cleared when non-erroneous calls are made. The global error list sys_errlist[] indexed by errno can be used to obtain the error message without the newline. The largest message number provided in the table is sys_nerr -1. Be careful when directly accessing this list because new error values may not have been added to sys_errlist[]. When a system call fails, it usually returns -1 and sets the variable errno to a value describing what went wrong. (These values can be found in <errno.h>.) Many library functions do likewise. The function perror() serves to translate this error code into human-readable form. Note that errno is undefined after a successful library call: this call may well change this variable, even though it succeeds, for example because it internally used some other library function that failed. Thus, if a failing call is not immediately followed by a call to perror, the value of errno should be saved. CONFORMING TO ANSI C, BSD 4.3, POSIX, X/OPEN SEE ALSO strerror(3) 2001-12-14 PERROR(3)

      And here's a way one might do it in Perl:

      package PError; use strict; use warnings; our ($VERSION) = q $Revision: 1.1 $ =~ /([\d.]+)/g; sub perror {warn @_ ? "@_: $!\n" : "$!\n"} sub pdie {die @_ ? "@_: $!\n" : "$!\n"} my %symbols = map {$_ => 1} qw /perror pdie/; sub import { my $class = shift; my $caller = caller; foreach my $name (@_ ? @_ : keys %symbols) { die "'$name' is not exported.\n" unless $symbols {$name}; my $func = $name eq "pwarn" ? "perror" : $name; no strict 'refs'; *{$caller . "::$name"} = \&{$class . "::$func"} } } 1; __END__
      when files arent there its usually a serious matter and I want to be able to track it back from the line it died from.
      I guess you and I differ. If a file is missing, than I will investigate why the file isn't there, and I'll start at the place that's supposed to produce the file. A line number in the program that figured out the file wasn't there doesn't do much for me.

      Abigail

        A line number in the program that figured out the file wasn't there doesn't do much for me.

        Well, my logging system automatically graduates die into confess so i actually get a full back trace. And here at least usually the reason a file isnt there is becuase somebody told the program to operate on something that it shouldnt. :-) Rarely is it due to a failure on the upstream side.

        BTW, the problem I have with something like what you describe here is that it wont be able to show the filename involved will it? At least not without overriding open.


        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi


Re: Re: Perl Style: About error messges opening files
by flyingmoose (Priest) on Apr 27, 2004 at 14:06 UTC
    OT, but yet another style question for Abigail, since '=>' was like crazy again...

    I've noticed you use => in place of commas .. a lot. <seinfeld>not that there is anything wrong with that</seinfeld>. I'm still one that uses => only for hash construction, when I need to imply a key-value pair, or maybe in a map, but anyway, when I need the implicit LHS quoting and a comma.

    In one of your examples, you gave something like

    system mkdir => -p => $foo;

    while most would do something closer to:

    system("mkdir -p $foo");

    Care to explain why this is syllistically more interesting to you? My guess is no, but we're on a style thread and this just looks odd to me. I'm thinking you were nearly eaten by a pack of rabid commas when you were a child or something :) Ok, so I'm not going to use '=>' any more because of what you might say, I'm just curious ... sort of like a 'where did that accent come from' type of question.

    (commence with the moose stoning)

      The difference between system("mkdir -p $foo") and system mkdir => -p => $foo; is more than just the style of commas. Single argument system is subject to shell interpretation, while multi argument system is not.

      Having said that, I tend to use => to separate arguments which have totally different roles - most often to separate the first argument from the rest:

      push @array => 1, 2, 3, 4; printf "%s %6d %s" => $foo, $bar, $baz; pack "C" => $var; splice @array => 0, 3 => "foo", "bar", "baz";
      Etc. I've used that long before people started preaching that => was some kind of pair creator. It never was, and still isn't. And I'm not the only one using this style, Larry Rosler (of GRT fame) was a vivid user of this style as well.

      Abigail

        A'ight, thanks! ... that explains a lot!

      I would imagine that Abigail avoided:

      system("mkdir -p $foo");

      because that would be interpreted by the shell, and would foul up if (for example) $foo contained a filename with spaces. The advantage of using the arrow instead of the comma is that you can get away with less quoting, compare:

      system mkdir => -p => $foo; system 'mkdir', '-p', $foo;

      Same number of chars, arguably more readable.

        To safe another char, one could write

        system qw(mkdir -p), $foo;

        But best would be if perl had a backtick operator like lisp (that is elisp, don't know about other lisp implementations):

        system `(mkdir -p ,$foo);

      You surely mean the list variant of system: system "mkdir", "-p", $foo
        Eh. $foo did not come from untrusted user input in my example.

        Fair point, but it depends on what domain you work in. In fact, none of my programs take any user input :)

Re: Re: Perl Style: About error messges opening files
by ambrus (Abbot) on Apr 27, 2004 at 18:55 UTC

    I never put a newline there, the line numbers at the error message do not cause any harm. (Line numbers as there are two: one for the source file and one for <>.)

    In one-liners I usually just use numbers after die:

    open my $F, "<", $name or die 1;
    I use numbers as they show where the error occured if there are multiple die statements in a one-liner, but they are short and easy to write. I add $! if the error really occurs and I don't know why it happened.