2016-12-05 5 views
-1

私はperlの新機能です。私は1つのcsvファイルの最初の列から文字列を取り込み、この単語の頻度を別のファイルで調べ、出力を3番目のファイルに出力したいとします。ここに私のコードです -1つのcsvファイルからの入力を取得し、perlの別のファイルの単語をカウントする方法

#!/usr/bin/perl 

$inputfile = 'Input.txt'; 
$outputfile = 'Out.csv'; 
$file = 'File.csv'; 

open(INPUT, "<$inputfile") or die "Could not read from $inputfile, program halting."; 
open(OUTPUT, ">$outputfile") or die "Could not open $outputfile, program halting."; 
open(FILE, "<$file") or die "Could not read from $file, program halting"; 

@temp; 
@token; 
$count; 

#skip first line of approved file 
if(<FILE>) 
{ 
    (@temp) = split (/\,/); 
} 
    $count = 0; 
    while(<FILE>) 
    { 
     @temp = split (/\,/); 
     print "First Column - @temp[0], "; 
     print "Count - @temp[1], "; 
     print "Priority - @temp[3], "; 
$count = 0; 
    while(<INPUT>) 
    { 
     #read the fields in the current record into an array 
     @words = split(/\s+/); 
     foreach $word (@words) 
     { 
      $temp1 = @temp[0]; 
      if($word == $temp1) 
      { 
       $count++; 
      } 
     } 
} 
    print "$temp1 - Count - $count \n "; 
    print OUTPUT "$temp1,$count,@temp[3]"; 
    print OUTPUT "\n"; 
} 

close INPUT; 
close OUTPUT; 
close FILE; 

print "Done, please check the output file.\n"; 

誰かを助けてください。

答えて

0

まず第一のものは、常にあなたがスカラーとして配列から値を取得誤解し​​ている

use strict; 
use warnings; 

です。配列からスカラー値を取得するには、次のコマンドを使用します。

 @temp = split (/\,/);     #this is array 
     print "First Column - $temp[0], "; #temp[[0] is scalar value of array 
     print "Count - $temp[1], ";   #temp[[1] is scalar value of array 
     print "Priority - $temp[3], ";   #temp[[2] is scalar value of array 

、ここ

foreach $word (@words) 
     { 
      $temp1 = $temp[0];  #this should be scalar. 
      if($word == $temp1) 
      { 
       $count++; 
      } 
     } 

あなたが@temp[0],@temp[1]を使用して、どこにいても...それは$temp[0],$temp[1],$temo[2] ....

+0

OKである必要があり、間違った使い方です。 。おめでとうございます。もう1つ質問があります - $ word = 12345と$ temp [1] = 1234を比較する方法をsubstrと比較する方法 – User312

+0

正しい方法で比較すると、ファイルを読むときに新しい行を切り詰めるあなたの比較がうまくいくこと。 – Nagaraju

+0

@ User312はその助けをしましたか? – Nagaraju

関連する問題