gpt4 book ai didi

perl - 为什么我得到 "can' t use string as a SCALAR ref while strict refs"在 Perl 中?

转载 作者:行者123 更新时间:2023-12-04 17:05:06 25 4
gpt4 key购买 nike

use strict;
my @array=('f1','f2','f3');
my $dir ='\tmp';
foreach (@array) {
my $FH = $_;
open ("$FH", ">$dir/${FH}.txt") or die $!;
}

foreach (@array) {
my $FH = $_;
close($FH);
}
我有 "Can't use string ("f1") as a symbol ref while "strict refs" in use at bbb.pl line 6."错误 。这是什么问题?

最佳答案

第一:2 arg open 不好,3 arg open 更好。

open( .. , ">", "$dir/${FN}.txt")   

其次,你到底在用 open("$FH"..

打开的参数 1 应该是可以连接到数据流的各种实际文件句柄。传递一个字符串是行不通的。
INSANE:  open( "Hello world", .... )  # how can we open hello world, its not a file handle
WORKS: open( *FH,.... ) # but don't do this, globs are package-globals and pesky
BEST: open( my $fh, .... ) # and they close themself when $fh goes out of scope!

第三
foreach my $filename ( @ARRAY ){ 
}

向前:

目录 = \tmp ?你确定吗?我想你的意思是 /tmp , \tmp是完全不同的东西。

第五:
use warnings;

使用严格是好的,但你也应该使用警告。

第六:使用解释性变量的名称,我们知道@是一个数组@array 没有多大帮助。

全部一起
use strict;
use warnings;

my @filenames=('f1','f2','f3');
my @filehandles = ();
my $dir ='/tmp';
foreach my $filename (@filenames) {
open (my $fh,'>', "${dir}/${filename}.txt") or die $!;
push @filehandles, $fh;
}
# some code here, ie:
foreach my $filehandle ( @filehandles ) {
print {$filehandle} "Hello world!";
}
# and then were done, cleanup time
foreach my $filehandle ( @filehandles ){
close $filehandle or warn "Closing a filehandle didn't work, $!";
}

或者,根据您尝试执行的操作,这可能是更好的代码:
use strict;
use warnings;

my @filenames=('f1','f2','f3');
my $dir ='/tmp';
foreach my $filename (@filenames) {
open (my $fh,'>', "${dir}/${filename}.txt") or die $!;
print {$fh} "Hello world!";
}

我没有明确关闭 $fh,因为它不需要,一旦 $fh 超出范围(在这种情况下在块的末尾)它就会自动关闭。

关于perl - 为什么我得到 "can' t use string as a SCALAR ref while strict refs"在 Perl 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com