FMc*_*FMc 5 perl filehandle typeglob
如果我有一个可能传递文件名或各种文件句柄或typeglobs的函数,那么函数如何区分这些参数 - 包括告诉差异,例如,在*DATA和之间*STDIN?
根据目前为止收到的答案更新了代码谢谢大家.
use strict;
use warnings;
use FileHandle;
sub file_thing_type {
my ($f) = shift;
my $type;
my $r = ref $f;
if ($r eq 'GLOB' or ref(\$f) eq 'GLOB'){
# Regular and built-in file handles.
my $fn = fileno $f;
if (defined $fn){
my %built_in = (
'STDIN' => fileno(*STDIN),
'STDOUT' => fileno(*STDOUT),
'STDERR' => fileno(*STDERR),
'DATA' => fileno(*DATA),
);
for my $k (keys %built_in){
if (defined $built_in{$k} and $built_in{$k} == $fn){
$type = $k;
last;
}
}
$type = 'regular file handle' unless defined $type;
}
else {
$type = 'non-IO glob';
}
}
elsif ($r){
# A reference of some kind.
$type = $r;
# Might be an IO object. Has it been opened?
{
no warnings 'unopened';
$type .= ' opened' if -f $f;
}
}
else {
# File name or just some other value?
$type = -f $f ? 'file name' : 'other';
}
return $type;
}
open(my $h, '<', $0) or die $!;
printf "%12s => %s\n",
$_->[0],
file_thing_type($_->[1])
for (
[ 'handle', $h ], # regular file handle
[ 'DATA', *DATA ], # DATA if source has DATA section; else non-IO glob
[ 'STDIN', *STDIN ], # STDIN
[ 'STDOUT', *STDOUT ], # STDOUT
[ 'STDERR', *STDERR ], # STDERR
[ 'FOO', *FOO, *FOO ], # non-IO glob
[ 'FileHandle', FileHandle->new ], # FileHandle
[ 'FileHandle', FileHandle->new($0) ], # FileHandle opened
[ 'file name', $0 ], # file name
[ 'not file', '' ], # other
[ 'misc', {bar=>1} ], # HASH
);
__END__
Run Code Online (Sandbox Code Playgroud)
更新:区分可能分配给*DATA或*STDINglob 的变量的问题是以下工作fileno:
子数据或标准输入{
我的 $x = 转变;
if (文件号($x) == 文件号(数据)) {
返回“数据”;
} elsif (文件号($x) == 文件号(STDIN)) {
返回“STDIN”;
} 别的 {
返回“都不是”;
}
}
打印“数据:”,data_or_stdin(*DATA),“\n”;
打印“STDIN:”,data_or_stdin(*STDIN),“\n”;
打开(ZZZ,“>>”,“zzz”);关闭ZZZ;
打开(ZZZ,“<”,“zzz”);打印“ZZZ:”,data_or_stdin(* ZZZ),“\ n”;关闭ZZZ;
打开($fh, "<", "zzz"); 打印“\$fh=ZZZ:”,data_or_stdin($fh),“\n”;关闭$fh;
$fh = *数据;print "\$fh=DATA: ", data_or_stdin($fh), "\n";
$fh = *STDIN; print "\$fh=STDIN: ", data_or_stdin($fh), "\n";
__结尾__
东西;
$ perl data_or_stdin.pl 数据:数据 标准输入:数据 ZZ:都没有 $fh=ZZZ:都不是 $fh=数据:数据 $fh=STDIN:数据
如果$f是文件句柄,则 或ref $f将为ref \$f如果"GLOB"
是$f标量,则将ref \$f为"SCALAR"。
sub filehandle_or_scalar {
my $x = shift;
if (ref $x eq "GLOB" || ref \$x eq "GLOB") {
return "filehandle";
} elsif (ref \$x eq "SCALAR") {
return "scalar";
} else {
return "not filehandle or scalar";
}
}
print "STDIN: ", filehandle_or_scalar(*STDIN), "\n";
print "\$_: ", filehandle_or_scalar($_), "\n";
open($fh, ">", "zzz");
print "\$fh: ", filehandle_or_scalar($fh), "\n";
print "string: ", filehandle_or_scalar('file.txt'), "\n";
print "ref: ", filehandle_or_scalar(\$x), "\n"
###########################################
$ perl filehandle_or_scalar.pl
STDIN: filehandle
$_: scalar
$fh: filehandle
string: scalar
ref: not filehandle or scalar
Run Code Online (Sandbox Code Playgroud)