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

Shr*_*ree 10 string perl

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

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

39250F800000000000000100011921680030081D
Run Code Online (Sandbox Code Playgroud)

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

39250F80000000000000010001192168003008F0
Run Code Online (Sandbox Code Playgroud)

我当前的实现会删除最后两个字符并附F0加到它:

my $nsap = "39250F800000000000000100011921680030081D";

chop($nsap);

chop($nsap);

$nsap = $nsap."F0";
Run Code Online (Sandbox Code Playgroud)

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

Nat*_*man 23

你可以使用substr:

substr ($nsap, -2) = "F0";
Run Code Online (Sandbox Code Playgroud)

要么

substr ($nsap, -2, 2, "F0");
Run Code Online (Sandbox Code Playgroud)

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

$nsap =~ s/..$/F0/;
Run Code Online (Sandbox Code Playgroud)

这是来自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.
Run Code Online (Sandbox Code Playgroud)

现在,有趣的是,结果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".
Run Code Online (Sandbox Code Playgroud)

或者您可以使用替换字段:

           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().
Run Code Online (Sandbox Code Playgroud)


igo*_*gor 9

$nsap =~ s/..$/F0/;
Run Code Online (Sandbox Code Playgroud)

用.替换字符串的最后两个字符F0.


mar*_*ton 6

使用substr()函数:

substr( $nsap, -2, 2, "F0" );
Run Code Online (Sandbox Code Playgroud)

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

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