2014-01-08 21 views
-1

我是初學perl程序員。我有下面的Perl代碼片段,並不明白爲什麼我不能打印ascii字符($ ascii_chr)OUTFILE。它似乎工作正常,當我打印到控制檯。無法使用perl打印輸出文件

不明白爲什麼它沒有傾銷chacracters在下面的打印語句

print OUTFILE $ascii_chr; ## But this print statement does not work. 

這裏了outfile這個特別的循環的代碼段。

#Now look for start_conversion = 1 and then convert the hex data into ascii data 
if (($start_conversion == 1) && ($_ != '5f535452') && ($_ != '5f454e44')) { 
    chomp; 
    $_ =~ s/000000/ 0x/g; 
    @my_array = split(/ /, $_); 
    foreach $split_word(@my_array) { 
     $ascii_chr = chr(hex($split_word)); 
     print $ascii_chr;  ## This print statement works. 
     print OUTFILE $ascii_chr; ## But this print statement does not work. 
    } 
} 

這是完整的代碼。我嘗試了幾件事,但無法打印到OUTFILE。

#!/usr/bin/perl 
$num_arg = $#ARGV + 1; 
if (($ARGV[0] =~ /help/)) { 
print "post_code_log.pl <inputfile> <outputfile> \n"; 
exit; 
} 
$infile_name = $ARGV[0]; 
$outfile_name = $ARGV[1]; 

#Logic to remove non-ascii characters from a text file 
$count   = 0; 
$start_num  = '5f535452'; 
$stop_num   = '5f454e44'; 
$start_conversion = 0; 
open (DATA, "$infile_name"); 
open (OUTFILE, ">$outfile_name"); 
while (<DATA>) { 
    s/^;.*//g; # Remove a line starting with ; 
    s/^\n//g; # Remove blank lines 
    s/.*?://; # Remove first column 
    s/.*?Port80Wr//; # Remove the first column look for Port80Wr 
        # (since the first column contains "Port80Wr") 
    s/^\s+//g; # Remove the space in front 

    #Look for start signature 
    if ($_ =~ '5f535452') { 
     print $_; 
     $start_conversion = 1; 
    } 
    #Look for stop signature 
    if ($_ =~ '5f454e44') { 
     print OUTFILE "\n"; # May need to print newline 
     print $_; 
     $start_conversion = 0; 
    } 
    # Now look for conversion start and then convert hex to ascii 
    if (($start_conversion == 1) && ($_ != '5f535452') && ($_ != '5f454e44')) { 
     chomp; 
     $_ =~ s/000000/ 0x/g; 
     @my_array = split(/ /, $_); 
     foreach $split_word(@my_array) { 
      $ascii_chr = chr(hex($split_word)); 
      print $ascii_chr; 
      print OUTFILE $ascii_chr; 
     } 
    } 
    # Now look for conversion end and send the data 
    # as is without making any changes 
    if (($start_conversion == 0) && ($_ != '5f535452') && ($_ != '5f454e44')) { 
     print OUTFILE $_; 
    } 
} 
print "Done\n"; 
+0

顯示確切的命令行運行'post_code_log.pl' 。你給它2個參數嗎?你的代碼適用於我(它會創建一個非空的輸出文件)。 – toolic

+0

你應該使用['use strict;使用警告;'](http://stackoverflow.com/q/8023959/725418)。 – TLP

+0

如果您添加「使用警告」,您可能會收到有關錯誤的信息。我猜你會在未打開的文件句柄OUTFILE上得到print()。 – TLP

回答

1

檢查,如果你的文件確實是開放的:

open (OUTFILE, ">", $outfile_name) or die "Cannot open '$outfile_name': $!"; 

同時添加這附近你的代碼的頂部:

use warnings; 
+6

最好使用open的3參數形式。 http://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-autovivified-filehandles-a-perl-best-pract – chilemagic

+0

輸出文件已打開。因爲它是從上面的perl代碼中的其他循環打印的。 –

+0

@CharubenPandya:調試使用:http://www.perlmonks.org/?node_id=745674 – toolic