2016-12-05 125 views
-1

我對perl非常陌生。我想從一個csv文件的第一列中取出字符串,並希望在另一個文件中檢查這個單詞的頻率,並希望在第三個文件中打印輸出。這裏是我的代碼 -如何從一個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[0],@temp[1]

 @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],$temo[2] ....

+0

確定。 .Thanks ..多一個查詢是 - 如何比較子字符串讓說$ word = 12345和$ temp [1] = 1234然後如何比較 – User312

+0

您正在比較正確的方式使用chomp截斷新行讀取文件時你的比較將起作用。 – Nagaraju

+0

@ User312有幫助嗎? – Nagaraju

相關問題