Perl字符串拆分及拼接案例

      背景:将文件中的32bit数据(Hex,16进制表示的数据)拆分为每8bit一组,并在每2个组中间插入ECC,不关心ECC的具体值,用任意数据替代即可。

  1. #!usr/bin/perl
  2. use warnings;
  3. use strict;
  4. use autodie;
  5. my $ecc_tmp_data = "0000";
  6. my $input_file = $ARGV[0];
  7. my $output_file = $ARGV[1];
  8. open(IN, '<', $input_file);
  9. open(OUT, '>', $output_file);
  10. while(<IN>) {
  11. $_ = hex($_);
  12. my $bin_32bit_data = sprintf("%0b", $_);
  13. my $bin_32bit_data = "0"x(32 - length($bin_32bit_data)).$bin_32bit_data;\
  14. my $part_a = substr($bin_32bit_data, 0, 8);
  15. my $part_b = substr($bin_32bit_data, 8, 8);
  16. my $part_c = substr($bin_32bit_data, 16, 8);
  17. my $part_d = substr($bin_32bit_data, 24, 8);
  18. my $output = $ecc_tmp_data.$part_a.$ecc_tmp_data.$part_b.$ecc_tmp_data.$part_c.$ecc_tmp_data.$part_d;
  19. print OUT "$ecc_tmp_data\n";
  20. }