修改Perl中字符串的最后两个字符

时间:2010-12-07 10:50:38

标签: perl string

我正在寻找问题的解决方案:

我有一个长度为20个字符的NSAP地址:

39250F800000000000000100011921680030081D

我现在必须用F0替换此字符串的最后两个字符,最终字符串应如下所示:

39250F80000000000000010001192168003008F0

我当前的实现会删除最后两个字符并将F0添加到其中:

my $nsap = "39250F800000000000000100011921680030081D";

chop($nsap);

chop($nsap);

$nsap = $nsap."F0";

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

3 个答案:

答案 0 :(得分:20)

您可以使用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().

答案 1 :(得分:9)

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

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

答案 2 :(得分:5)

使用substr( )功能:

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

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

我相信substr()会比使用正则表达式更快。<​​/ p>