Perl check if file handler is open

If you write a function 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 

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 

The Result, looks like expected:

Check undefined:
0
0
Check defined:
1
1
Check close write:
1
0
Check close read:
1
0

Post has been published on http://scheinast.eu/perl-check-if-file-handler-is-open/

Advertisements

Eine Antwort zu “Perl check if file handler is open

  1. Pingback: Perl check if file handler is open | Paul Scheinast

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden / Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden / Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden / Ändern )

Google+ Foto

Du kommentierst mit Deinem Google+-Konto. Abmelden / Ändern )

Verbinde mit %s