2014-03-27 16 views
-1

從此012 0129 9 9 9 9 98 9 7 7 7 7 7 7 7 7 7 7 7 7 8 9 9 9 3 7 9 9 6 3 3 3 3 0 1 2。我仍然有這個腳本語法麻煩:perl +讀取多個csv文件+操作文件+提供output_files +語法錯誤符號參考

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 ## 

} 

我可以通過添加括號($dh)

,但我仍然有這條線print {$format_file} scalar <$orig_file>; # Copy header line

我得到的麻煩解決這一行opendir my $dh, $source_dir;以下錯誤:

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. 

任何人都可以建議嗎?

我已經嘗試使用advise here但沒有太多的喜悅。

+1

我不想讓你太煩擾;) - 這是你工作的第三部分。我的建議是 - 嘗試將代碼分解爲更小,更易於管理的子例程。單獨調試每個子。這樣,獲得正確的結果就容易得多。例如,很容易讀取如下內容:'convert_csv($ _)for(@files);'和'convert_csv'是轉換ONE文件的子文件。等...等等...小的潛艇,容易調試,更易於管理,更短的問題,更快的更準確的答案:) – jm666

+0

@ jm666 tks和同意,但在這個階段慢慢學習... – HattrickNZ

回答

1

使用print $format_file ...print ${format_file} ...

然而$format_file只是包含文件,而不是一個文件句柄的名字的字符串。你必須打開文件:

open my $format_fh, '>', $format_file or die $!; 
... 
print $format_$fh ... ; 
+0

tks但我可能已經試過它不起作用 – HattrickNZ

+0

它以什麼方式「不起作用」 – justintime