使用perl将文本文件转换为二进制文件的问题

Problem converting a text file into binary file using perl

我想使用 Perl 将一些数据转换为二进制。数据需要以8位二进制输出。原始数据采用以下格式:

137.0000
136.0000
133.0000
136.0000
10.0000
134.0000
0.0000
132.0000
132.0000

为此,我转换了数据以抑制“.0000”,然后我使用带有选项 C*pack 函数(此格式对应于 "unsigned character (usually 8 bits)"到文档)。 我将此文件命名为 txt2bin.pl:

my $file = $ARGV[0];
my $fileout = $file.".bin";

if($file eq "-h" or $file eq "-help" or $file eq "")
{  
    print "Usage : txt2bin.pl file_in\n";
    print "        file_out = file_in.bin\n";
    print "This script converts a txt file to a binary file\n";

}

else
{
  print "File in = $file\n";
  print "File out = $fileout\n";

  open(FILE,"<$file") or die $!;
  open(FILEOUT,">$fileout") or die $!;
    binmode FILEOUT;
    while(defined(my $line=<FILE>))
    {
      chomp($line);
      $line =~ s/\.0000//;
      syswrite FILEOUT, pack("C*",$line);
    }
  close(FILE);
  close(FILEOUT);
}

我还需要能够进行反向操作,所以,我创建了另一个文件bin2txt.pl:

my $file = $ARGV[0];
my $fileout = $file.".txt";

if($file eq "-h" or $file eq "-help" or $file eq "")
{
    print "Usage : bin2txt.pl file_in\n";
    print "        file_out = file_in.txt\n";
    print "This script converts a binairy file to a txt file\n";
}

else
{
  print "File in = $file\n";
  print "File out = $fileout\n";

  my $file = "<$file";

  # undef $/ to read whole file in one go
  undef $/;

  open(FILE,$file) or die $!;
  open(FILEOUT,">$fileout") or die $!;

  # binmode FILE to supress conversion of line endings
  binmode FILE;

  my $data = <FILE>;
  $data =~ s/(.{1})/unpack("C*",).".0000 \n"/eg;
  syswrite FILEOUT, $data;
}

然而,当我执行第一个程序txt2bin.pl,然后执行第二个程序时,我应该得到:

137.0000
136.0000
133.0000
136.0000
10.0000
134.0000
0.0000
132.0000
132.0000

相反,我得到了这个:

137.0000
136.0000
133.0000
136.0000

134.0000
0.0000
132.0000
132.0000

10.0000 没有出现,你们有什么想法吗? 感谢您的帮助。

您需要将 s 修饰符添加到正则表达式替换以匹配 10(换行符):

$data =~ s/(.{1})/unpack("C*",).".0000 \n"/seg;

来自 perldoc perlre :

s
Treat the string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.