Good day Perl monks
I was wondering if it was possible to test if a variable was a folder handle. I could not find any documentation or forum posts so far. I have written some code which works as shown below. I was wondering if there was a better way to perform the folder testing section as my code seems inelegant.
Also, I am aware that the file testing section could be improved but there is already plenty of comment on that in the following posts
http://www.perlmonks.org/?node_id=980665 Best way to check if something is a file handle?
#!perl use strict; use warnings; use Data::Dumper; use File::Temp qw(tempfile tempdir); use Scalar::Util qw(looks_like_number openhandle); my $fh = tempfile(); #my $dh = tempdir(); opendir(my $dh, '.') || die "Can't opendir: $!"; my $string = 'path\to\file\name'; print Dumper handleRef($fh); print Dumper handleRef($dh); print Dumper handleRef($string); sub handleRef { my ($handle) = @_; my ($fh, $dataTypeHash) = @_; # Folder test (may be possible to improve)... my $folderType = eval { no warnings; telldir ($fh); }; if (looks_like_number($folderType)){ $folderType = 1; } else { $folderType = 0; } return 'FOLDERHANDLE' if ($folderType); # File test... my $handleType = openhandle($handle); return 'FILEHANDLE' if (openhandle($handle)); # Everything else... return ref \$fh; }
In reply to Testing for a directory handle by ns550
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |