File: retry_open_handle.pl

package info (click to toggle)
libfile-util-perl 4.201720-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 840 kB
  • sloc: perl: 4,353; makefile: 2
file content (47 lines) | stat: -rw-r--r-- 990 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# ABSTRACT: Try opening a file, falling back to a failsafe file on error

use strict;
use warnings;

use File::Util qw( NL );

my $ftl = File::Util->new();

my $might_not_work     = '/this/might/not/work.txt';
my $will_work_for_sure = '/tmp/file.txt';
my $used_backup_plan   = 0;

my $file_handle = $ftl->open_handle
(
   $might_not_work =>
   {
      mode   => 'write',
      onfail => sub
      {
         my ( $err, $stack_trace ) = @_;

         warn "Couldn't open first choice, trying a backup plan...";

         $used_backup_plan = 1;

         return $ftl->open_handle( $will_work_for_sure => { mode => 'write' } );
      },
   }
);

print $file_handle 'Hello World!  The time is now ' . scalar localtime;

print $file_handle NL; # portably add a new line to the end of the file

close $file_handle or die $!;

# print out whichever file we were able to successfully write
print $ftl->load_file
(
   $used_backup_plan
      ? $will_work_for_sure
      : $might_not_work
);

exit;