#!C:/Perl/bin/perl /w # CloseUnlinkTest.pl use strict; my $file1 = 'file1.txt'; my $file2 = 'file2.txt'; my $file3 = 'file3.txt'; open(my $handle1, ">", $file1) or &quit({}, "Cannot open $file1: $!"); # Quit, dont need to close any files open(my $handle2, ">", $file2) or &quit({$handle1=>0}, "Cannot open $file2: $!"); # Quit, close $file1 open(my $handle3, ">", $file3) or &quit({$handle1=>0, $handle2=>0}, "Cannot open $file3: $!"); # Quit, close $file1 and file2 # Do stuff with the files ... &quit({$handle1=>1, $handle2=>1, $handle3=>1}, "CloseUnlinkTest.pl finished"); # Quit, close and unlink all 3 files sub quit { my ($filesToClose, $message) = @_; # Get calling parameters my %filesToClose = %$filesToClose; # Dereference $filesToClose into hash %filesToClose print "\%filesToClose = @{[%filesToClose]}\n"; # Debug to show hash contents print "message = $message\n"; while (my ($file, $unlink) = each %filesToClose) { # Loop thru the files to be closed print "closing $file with $unlink\n"; # Debug to show the key and value of this hash entry close($file) or print "Error closing $file: $!\n"; # Close this file unlink($file) or print "Error unlinking $$file: $!\n" if $unlink; # Unlink this file if $unlink is not zero } exit; }