我需要以下Perl代码的一些指导.当我离开时no strict 'refs',sub工作正常.但如果no strict 'refs'删除,我收到错误消息:
Can't use string ("A") as a symbol ref while "strict refs" in use at test.pl
Run Code Online (Sandbox Code Playgroud)
它在下面标记为"Here"的行中死亡.这sub需要从A..Z打开(写>)所有文件,并根据regexREAD文件(LOG)将输出写入相应的文件输出.
use strict;
use Text::CSV_XS;
no strict 'refs';
...
...
sub file_split {
my ( $i, $fh, @FH );
my ( $file ) = @_;
my ( @alpha) = ("A".."Z");
for ( @alpha) {
$fh = $_ ;
open ( $fh,">","$_-$file" ) || die $!; <--------- HERE
push @FH, $fh;
}
my $csv = Text::CSV_XS->new( { binary => 1,
allow_whitespace => 1,
allow_loose_escapes => 1,
allow_loose_quotes =>1,
escape_char => undef ,
sep_char => ',',
auto_diag=> 1
} );
open( LOG,"<", $file ) || die $!;
while ( my $row = $csv->getline( *LOG ) ) {
if ( $row->[0] =~ /^(\w)/ ) {
print $1 <--------- HERE
"$row->[0]".",".
"$row->[1]" .",".
"$row->[2]" .",".
"$row->[3]" .",".
"$row->[4]".",".
"$row->[5]"."\n";
} else {
print "Record skipped... --> $row->[0] <-- ... please verify \n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
不要指定$fh = $_它没有做任何有用的事情.
@FH应该%FH而不是push尝试:
$FH{ $_ } = $fh
Run Code Online (Sandbox Code Playgroud)
更换$1用$FH{ $1 }.
你要求perl在这里使用$ fh的值作为文件句柄的名称:
for ( @alpha) {
$fh = $_ ;
open ( $fh,">","$_-$file" ) || die $!; <--------- HERE
push @FH, $fh;
}
Run Code Online (Sandbox Code Playgroud)
您应该考虑使用词法变量并通过open将其自动生成文件句柄,然后将其存储在哈希中以便稍后获取:
for ( @alpha) {
open ( my $fh,">","$_-$file" ) || die $!;
$handles{$_} = $fh;
}
Run Code Online (Sandbox Code Playgroud)
这样你以后可以使用它:
while ( my $row = $csv->getline( *LOG ) ) {
if ( $row->[0] =~ /^(\w)/ ) {
print $handles{$1} <--------- HERE
...
Run Code Online (Sandbox Code Playgroud)