9

Most of time, I do something like this:

open FH, ">file.txt" or die "Cann't open file: $!";

Does die have to be used? If I want my script to continue (and simply ignore the error if the file cannot be opened), what should I do?

3
  • 3
    Please never use Barewords FH or the 2 Argument way of open. ALWAYS use open my $fh, '>','file.txt'. Its safer because Barewords are global. Also with the way of opening (reading, appending, writing, .. ). When you use a Variable for the Filename, it could start with something unreliable, dubious (like a Pipe...) =)
    – user1558455
    Jun 25, 2013 at 22:25
  • 4
    Please never make blanket statements like that. What he’s doing it perfectly fine in many situations.
    – tchrist
    Jun 27, 2013 at 23:39
  • @tchrist: However, lexical file handles together with the three-argument form of open is "perfectly fine" in more situations and has no disadvantages. It is common sense to adopt it as a standard practice, and you do Perl a disservice by criticising an attempt to evangelise it.
    – Borodin
    Jul 10, 2018 at 14:56

9 Answers 9

22

You might want to do something like

if(open my $fh, ">", "file.txt") {
    # do stuff with file
    close $fh;
}
else {
    # do stuff without file
} 
6
  • In else, Is it good for me to use goto ( such as goto Exit; and at the end of the script, Exit: exit(-1);)?
    – ericyoung
    Jun 25, 2013 at 20:24
  • 6
    @ericyoung - No. No, it is not. You'll be much better off if you pretend that Perl has no implementation of goto. And you can always do open(my $fh,">","file.txt") or exit(-1);
    – user554546
    Jun 25, 2013 at 20:26
  • @JackManey: Actually, that's not strictly true. The goto &SUB version of goto is really useful :-)
    – Dave Cross
    Jun 26, 2013 at 9:45
  • @ericyoung Wait. So your question is about how to avoid throwing an exception so you can reimplement exceptions? Are you really asking how to make it so that die does not abort the program?
    – darch
    Jun 26, 2013 at 18:49
  • 2
    @ericyoung That's a restatement of what I was saying, and the correct answer is "Catch the exception.".
    – darch
    Jun 27, 2013 at 22:40
8

The code doesn't have to die if it cannot access the file.

If writing to the file is optional, you might do something like this:

my $file_is_ok = 0;
open FH, ">file.txt" and $file_is_ok = 1;
warn "No logging available" unless $file_is_ok;

Then wherever you want to use the file handle, you can check first that it is ok:

$file_is_ok and print FH "Something happened";

Usually you'll want a little more abstraction than the above, but I hope that is enough to get started.

5

No, die most definitely doesn't have to be used, or else a failed open would simply exit the program. This is just a commonly used construct since often if you can't open a file there's no point in continuing, but there really is no requirement to die or to do anything else either.

0
1
open(my $fh, ">", $file) or print "open failed , you are on your own\n";
1

I might do something like:

sub process_file {
    my $file = shift;
    open(my $fh, ">", $file) or return;
    # write to file ...
}
0

It is recommended that you use croak() from Carp instead, especially in modules or objects. See http://perldoc.perl.org/Carp.html

Carp is a standard module and, like all standard modules, comes installed with Perl. A list of all the standard modulesis available in perlmodlib. See http://perldoc.perl.org/perlmodlib.html

0

Sorry for responding to a few months old question, but the way I do this is by implementing my own die style subroutine:

sub fail {
    my $text = $_[0];

    # Do error-related stuff here, like send an email
    die($text) # or just exit
}

open(my $fh, ">file.txt") or fail("Unable to open file: $!");
-1

You could use a try catch block, using Try::Tiny or something of the sort.

3
  • 2
    while i did not -1, IMO this is a comment, not an answer.. and it sounds a bit pythonic, not perlis...
    – Aprillion
    Jun 25, 2013 at 20:09
  • i did not -1 either, but the OP wants to ignore errors, and open() does not die by default, so this is not even an answer, unless the OP is using autodie, which would be dumb if he wants to ignore errors.
    – runrig
    Jun 25, 2013 at 21:13
  • @deathapril You're right that it's not perlish assuming this is 1998.
    – darch
    Jun 26, 2013 at 18:52
-1

If what you are trying to do is avoid exiting the program when you encounter an error opening a file, omitting the die is not the correct approach. die is Perl's exception mechanism; the fact that it aborts the program by default is an accidental, not fundamental, property. If you supply an exception handler, you retain control. The correct approach is to catch the exception and do your cleanup in the finally block.

use 5.10.0;
use Try::Tiny;

my ($infile, $FH);
try {
    open $infile, '<', 'infile.txt' or die "Can't open infile";
    try { 
        open $FH, '>', 'file.txt'   or die "Can't open outfile";
        my $line = <$infile>;
        print $FH $line;
        say 'Cleaning up $FH';
        close $FH;
    } finally {
        say 'Cleaning up $infile';
        close $infile;
    } catch {
        die $_;
    };
} catch {
    die $_;
};

So if open $infile ... fails, die to the catch block, which redies and aborts the script. But once we've opened $infile, if open $FH fails, die to a catch block that also aborts the program but forces close $infile to happen first. File handles aren't the best examples of resources to clean up before program exit because the interpreter closes files automatically, but the basic idea is there.

If you don't like the nested try blocks, you can achieve a very similar effect by checking which exception caused the block to abort and deciding what cleanup is necessary based on that. That's a little more fragile, but still more robust than anything mentioning goto.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.