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);
}
Run Code Online (Sandbox Code Playgroud)
我收到了"Can't use string ("f1") as a symbol ref while "strict refs" in use at bbb.pl line 6."错误.什么是isuse?
您正在使用字符串"f1"作为第一个open需要文件句柄的参数.
你可能想做:
my @filehandles = (); # Stash filehandles there so as to not lose filenames
foreach (@array) {
my $FH = $_;
open (my $fh, ">", "$dir/${FH}.txt") or die $!;
push @filehandles, $fh;
}
Run Code Online (Sandbox Code Playgroud)
第一:2 arg open是坏的,3 arg open更好.
open( .. , ">", "$dir/${FN}.txt")
Run Code Online (Sandbox Code Playgroud)
第二,你在做什么打开("$ 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!
Run Code Online (Sandbox Code Playgroud)
第三
foreach my $filename ( @ARRAY ){
}
Run Code Online (Sandbox Code Playgroud)
向前:
dir = \tmp?你确定吗?我想你的意思是/tmp ,\tmp完全不同.
第五:
use warnings;
Run Code Online (Sandbox Code Playgroud)
使用严格是好的,但你也应该使用警告.
第六:使用名称解释变量,我们知道@是一个数组@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, $!";
}
Run Code Online (Sandbox Code Playgroud)
或者,根据您的尝试,这可能是更好的代码:
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!";
}
Run Code Online (Sandbox Code Playgroud)
我没有明确关闭$ fh,因为它不需要,只要$ fh超出范围(在这种情况下在块的末尾)它就会自动关闭.