从question开始。我仍然遇到这个脚本的语法问题:
use strict;
use warnings;
use autodie; # this is used for the multiple files part...
#START::Getting current working directory
use Cwd qw();
my $source_dir = Cwd::cwd();
#END::Getting current working directory
print "source dir -> $source_dir\n";
my $output_prefix = 'format_';
#print "dh -> $dh\n";
opendir my $dh, $source_dir; #Changing this to work on current directory; changing back
# added the "()" here ($dh) as otherwise an error
for my $file (readdir($dh)) {
next if $file !~ /\.csv$/;
next if $file =~ /^\Q$output_prefix\E/;
my $orig_file = "$source_dir/$file";
my $format_file = "$source_dir/$output_prefix$file";
# .... old processing code here ...
## Start:: This part works on one file edited for this script ##
#open my $orig_fh, '<', 'orig.csv' or die $!; #line 14 and 15 above already do this!!
#open my $format_fh, '>', 'format.csv' or die $!;
print "format_file-> $format_file\n";
#print $format_fh scalar <$orig_fh>; # Copy header line #orig needs changeing
print {$format_file} scalar <$orig_file>; # Copy header line
my %data;
my @labels;
#while (<$orig_fh>) { #orig needs changing
while (<$orig_file>) {
chomp;
my @fields = split /,/, $_, -1;
my ($label, $max_val) = @fields[1,12];
if ( exists $data{$label} ) {
my $prev_max_val = $data{$label}[12] || 0;
$data{$label} = \@fields if $max_val and $max_val > $prev_max_val;
}
else {
$data{$label} = \@fields;
push @labels, $label;
}
}
for my $label (@labels) {
#print $format_fh join(',', @{ $data{$label} }), "\n"; #orig needs changing
print $format_file join(',', @{ $data{$label} }), "\n";
}
## END:: This part works on one file edited for this script ##
}
我可以通过添加括号opendir my $dh, $source_dir;
($dh)
但我仍然遇到此行print {$format_file} scalar <$orig_file>; # Copy header line
行
我收到以下错误:
Can't use string ("/home/Kevin Smith/Perl/format_or"...) as a symbol ref while "strict refs" in use at formatfile_QforStackOverflow.pl line 29.
任何人都可以提供建议吗?
我尝试过使用建议here,但没有太多的快乐。
答案 0 :(得分:1)
使用print $format_file ...
或print ${format_file} ...
但是$format_file
只是一个包含文件名的字符串,而不是文件句柄。你必须打开文件:
open my $format_fh, '>', $format_file or die $!;
...
print $format_$fh ... ;