If you write a function in Perl and want to check if the file handler is already open you could use this function:
|
sub filehandlerOpen { my $fh = shift; no warnings 'uninitialized'; return 0 if(!defined $fh || $fh !~ /^GLOB\(0x.+?\)$/); if(fileno($fh) >= 1){ return(1); } return(0); } |
It returns 0 if its undefined,closed or not open, an 1 if the handler is open.
In this little example I open a file to read and another to write, I check the sub before and after the open function, and before and after the close function.
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
|
#!/usr/bin/perl use warnings; use strict; my ($fh_read,$fh_write); print "Check undefined:\n"; print filehandlerOpen($fh_read).$/; print filehandlerOpen($fh_write).$/; open($fh_write, ">", './testfile') or die "Failed to open file: $!\n"; open($fh_read, "<", './testfile') or die "Failed to open file: $!\n"; print "Check defined:\n"; print filehandlerOpen($fh_read).$/; print filehandlerOpen($fh_write).$/; for my $num (1..6){ print $fh_write "$num\n"; } print "Check close write:\n"; print filehandlerOpen($fh_write).$/; close($fh_write); print filehandlerOpen($fh_write).$/; while (my $row = <$fh_read>) { chomp $row; } print "Check close read:\n"; print filehandlerOpen($fh_read).$/; close($fh_read); print filehandlerOpen($fh_read).$/; sub filehandlerOpen { my $fh = shift; no warnings 'uninitialized'; return 0 if(!defined $fh || $fh !~ /^GLOB\(0x.+?\)$/); if(fileno($fh) >= 1){ return(1); } return(0); } |
The Result, looks like expected:
|
Check undefined: 0 0 Check defined: 1 1 Check close write: 1 0 Check close read: 1 0 |