in reply to Filtering error string $!, for example remove paths

$! never contains the filename that failed. A usual approach would be to show the user just a random error id and to log the error id together with the real error message in a log file.

Replies are listed 'Best First'.
Re^2: Filtering error string $!, for example remove paths
by isync (Hermit) on Aug 27, 2010 at 19:11 UTC
    Oops, yes, you are right! My memory played a trick on me so that I didn't separate enough where debugging style error messages end and live mode error messages begin. It is not $! who behaves talkative...
    my $file = '/some/secret/path/to.file'; open(my $fh, "<$file") or die "Error opening $file: $!";
    File closed. Should've known that... Thanks!
      ... Oh... the many ways of "death"

      In many cases (like file open), the $! sequence doesn't matter because it expands to the generic "No such file or directory" message shown below. This adds no value to the error message.

      Adding a "\n" to the die message suppresses the source code line where the error occurred.

      For a failed open(), I often just put: die "unable to open $file"; .. What would adding $! to that message offer? In realistic terms, wrong name, wrong path, wrong permissions and the "hunt" starts there.

      When the "die error message" is written, it it up to coder to decide what information to divulge (or not!).

      #!/usr/bin/perl -w use strict; my $file = '/some/secret/path/to.file'; # open(my $fh, "<$file") or die "Error opening $file: $!"; # error prints: Error opening /some/secret/path/to.file: # No such file or directory at C:\TEMP\junk3.pl line 6. my $file1 = '/some/secret/path/to.file'; # open(my $fh, "<$file1") or die "Error opening $file1\n"; # error prints: Error opening /some/secret/path/to.file my $file2 = '/some/secret/path/to.file'; #open(my $fh, "<$file2") or die "$!"; # error prints: No such file or directory at C:\TEMP\junk3.pl line 1 +5. my $file3 = '/some/secret/path/to.file'; #open(my $fh, "<$file3") or die "$!\n"; # error prints: No such file or directory my $file4 = '/some/secret/path1/to.file'; #open(my $fh, "<$file4") or die ""; # error prints: Died at C:\TEMP\junk3.pl line 31. my $file5 = '/some/secret/path4/to.file'; open(my $fh, "<$file5") or die "\n"; # error prints: NOTHING!