ns550 has asked for the wisdom of the Perl Monks concerning the following question:
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; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Testing for a directory handle
by AnomalousMonk (Archbishop) on Jan 29, 2018 at 03:51 UTC | |
by ns550 (Novice) on Jan 29, 2018 at 03:59 UTC | |
by syphilis (Archbishop) on Jan 29, 2018 at 05:06 UTC | |
by ns550 (Novice) on Jan 29, 2018 at 05:24 UTC | |
by syphilis (Archbishop) on Jan 29, 2018 at 06:43 UTC | |
| |
|
Re: Testing for a directory handle
by salva (Canon) on Jan 29, 2018 at 09:40 UTC | |
|
Re: Testing for a directory handle
by kcott (Archbishop) on Jan 29, 2018 at 21:47 UTC | |
by syphilis (Archbishop) on Jan 30, 2018 at 01:10 UTC | |
by kcott (Archbishop) on Jan 30, 2018 at 03:48 UTC | |
by afoken (Chancellor) on Jan 30, 2018 at 23:09 UTC | |
by kcott (Archbishop) on Jan 31, 2018 at 02:27 UTC | |
by ns550 (Novice) on Jan 29, 2018 at 23:38 UTC | |
by kcott (Archbishop) on Jan 30, 2018 at 03:41 UTC |