Perl check if file handler is open

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.

#!/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

One thought on “Perl check if file handler is open”

Leave a Reply

Your email address will not be published.

three × three =