![](/img/trans.png)
[英]Why do I get a syntax error when I try to print a nested hash that has keys containing colons?
[英]Why do I get a syntax error when I want to print to a handle in a hash key?
我有代码将当前目录中文件的所有文件句柄存储为哈希值。 键是文件的名称。
my %files_list; #this is a global variable.
sub create_hash() {
opendir my $dir, "." or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach (@files) {
if (/.text/) {
open(PLOT, ">>$_") || die("This file will not open!");
$files_list{$_} = *PLOT;
}
}
}
我正在代码中使用打印语句,在那里我遇到了一些编译问题。
my $domain = $_;
opendir my $dir, "." or die "Cannot open directory: $!";
my @files = readdir $dir;
foreach (@files) {
if (/.text/ && /$subnetwork2/) {
print $files_list{$_} "$domain"; #this is line 72 where there is error.
}
}
closedir $dir;
编译错误如下:
String found where operator expected at process.pl line 72, near "} "$domain""
(Missing operator before "$domain"?)
syntax error at process.pl line 72, near "} "$domain""
谁能帮我理解故障吗?
第一个问题:运行create_hash
子例程后,您将在所有键中将%files_list
填充为*PLOT
。
全部显示print {$files_list{$_}} "$domain";
谁应该打印到最后打开的文件中。
解:
-open(PLOT,">>$_") || die("This file will not open!");
-$files_list{$_}=*PLOT;
+open($files_list{$_},">>$_") || die("This file will not open!");
第二个问题:在打印文件描述符之前,不要检查文件描述符是否存在
解:
-if(/.text/ && /$subnetwork2/)
-{
- print $files_list{$_} "$domain";#this is line 72 where there is error.
+if(/.text/ && /$subnetwork2/ && exists $files_list{$_})
+{
+ print {$files_list{$_}} $domain;
并且不要忘记关闭文件句柄...
也许您应该阅读印刷文档 。 最后一段说:
如果将句柄存储在数组或哈希中,或者通常在任何使用比裸字句柄复杂的表达式或普通的,未下标的标量变量检索表达式时,都必须使用返回文件句柄值的块相反,在这种情况下,LIST不能省略:
print { $files[$i] } "stuff\\n"; print { $OK ? STDOUT : STDERR } "stuff\\n";
也许是这样的:
print {$files_list{$_}} "$domain";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.