2010-12-07 35 views
8

我寻找到问题的解决方案:修改字符串的最后两个字符在Perl

我有NSAP地址是20个字符长:

39250F800000000000000100011921680030081D 

我现在不得不更换此字符串F0和最后一个字符串的最后两个字符应该是这样的:

39250F80000000000000010001192168003008F0 

我当前实现砍下最后两个字符并追加F0它:

my $nsap = "39250F800000000000000100011921680030081D"; 

chop($nsap); 

chop($nsap); 

$nsap = $nsap."F0"; 

有没有更好的方法来实现这个目标?

回答

18

您可以使用substr

substr ($nsap, -2) = "F0"; 

substr ($nsap, -2, 2, "F0"); 

或者你可以使用一个简单的正则表达式:

$nsap =~ s/..$/F0/; 

这是substr的手册页:

substr EXPR,OFFSET,LENGTH,REPLACEMENT 
    substr EXPR,OFFSET,LENGTH 
    substr EXPR,OFFSET 
      Extracts a substring out of EXPR and returns it. 
      First character is at offset 0, or whatever you've 
      set $[ to (but don't do that). If OFFSET is nega- 
      tive (or more precisely, less than $[), starts 
      that far from the end of the string. If LENGTH is 
      omitted, returns everything to the end of the 
      string. If LENGTH is negative, leaves that many 
      characters off the end of the string. 

现在,最有趣的部分是,substr的结果可以作为一个左值,并分配:

  You can use the substr() function as an lvalue, in 
      which case EXPR must itself be an lvalue. If you 
      assign something shorter than LENGTH, the string 
      will shrink, and if you assign something longer 
      than LENGTH, the string will grow to accommodate 
      it. To keep the string the same length you may 
      need to pad or chop your value using "sprintf". 

,或者您可以使用更换领域:

  An alternative to using substr() as an lvalue is 
      to specify the replacement string as the 4th argu- 
      ment. This allows you to replace parts of the 
      EXPR and return what was there before in one oper- 
      ation, just as you can with splice(). 
9
$nsap =~ s/..$/F0/; 

F0替换字符串的最后两个字符。

5

使用substr()功能:

substr($nsap, -2, 2, "F0"); 

chop()和相关的chomp()实际上是用于删除行尾字符 - 换行符等。

我相信substr()会比使用正则表达式更快。

相关问题