命令行替换,新值无效

时间:2016-09-23 16:22:20

标签: perl

我对perl很新          这是我正在做的事情,我有这样的输入行          我想替换匹配的每一行的值          字符串通过传递变量名,变量值和替换值          作为命令行的输入参数

     input_data:
     total_sum  0x0C    Uint8,unsigned char     
     num     0x0D   Uint8,unsigned char     
     max    0x4A    Uint8,unsigned char     
     padd   0x00    Uint8,unsigned char     
     ideal  0x01    Uint16, unsigned short
     min    0xffdd7f Uint16, unsigned short

预期产出:

     1.total_sum    0x0C    Uint8,unsigned char  //change 0x0B with 0x0C
     2.also if the string conation Uin16 then I need to pad 0x00 as i 
        want to read only one byte at a time
        for e.g ideal should be pad with (0x00,0x01)
     3.also if the string contain value more than one byte then i need 
        to split with 1 byte each
        for e.g oxffdd7f should be (0x0ff,0xdd,0x7f)

代码:

    #! /usr/bin/env perl

     use strict;
     use warnings;
     # input variable pass as a input argument
     my $variable_name =shift @ARGV;
     # variable value pass as a input argument
     my $variable_value =shift @ARGV;
     #variable value need to be replaced with new value 
     my $Replacement_var = shift @ARGV;
     # Name of the file the data is in
     my $input_filename  = 'my_input.txt';
     # Name of the file you want to dump the output to
     my $output_filename = 'my_output.txt';

     open my $input_fh, "<", $input_filename or die $!; 
     my @array;   
     while (my $eachline = <$input_fh>)
     {
     if ($eachline=~/^$variable_name/ and /$variable_value/)
        {
         $eachline=s/$variable_value/$Replacement_var/ ;
        }
        #here  extracting only hex values from each line
        while ($eachline =~ m/(0x(?:[0-9]|[A-f])+)/gi)  
        {
          push @array, $1;
        }
     }

     close $input_fh;
     open my $output_fh, ">", $output_filename or die $!;
     print {$output_fh} join(", ", @array);

我正在检查变量名称和值,然后替换变量值          使用新的但没有发生替换(field_ind 0x0B-&gt; 0x0C)          请帮助我,我在做错了。

1 个答案:

答案 0 :(得分:4)

$eachline=~/^$variable_name/ and /$variable_value/

应该是

$eachline=~/^$variable_name/ and $eachline=~/$variable_value/

当绑定运算符(=~)未明确用于正则表达式的左侧时,Perl会将其隐式绑定到$_变量。

您还想在其他地方使用绑定运算符并说

$eachline =~ s/$variable_value/$Replacement_var/ ;

而不是

$eachline = s/$variable_value/$Replacement_var/ ;
相关问题