我是初学者perl程序员。我有以下perl代码片段,无法理解为什么我不能将ascii字符($ ascii_chr)打印到OUTFILE。当我打印到控制台时似乎工作正常。
无法理解为什么在下面的print语句
中没有将字符转储到OUTFILE print OUTFILE $ascii_chr; ## But this print statement does not work.
以下是此特定循环的代码段。
#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 :(得分:1)
检查您的文件是否真的开放:
open (OUTFILE, ">", $outfile_name) or die "Cannot open '$outfile_name': $!";
还要在代码顶部附近添加:
use warnings;