开发者

Modify the last two characters of a string in Perl

I am looking fo开发者_开发技巧r a solution to a problem:

I have the NSAP address which is 20 characters long:

39250F800000000000000100011921680030081D

I now have to replace the last two characters of this string with F0 and the final string should look like:

39250F80000000000000010001192168003008F0

My current implementation chops the last two characters and appends F0 to it:

my $nsap = "39250F800000000000000100011921680030081D";

chop($nsap);

chop($nsap);

$nsap = $nsap."F0";

Is there a better way to accomplish this?


You can use substr:

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

or

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

Or you can use a simple regex:

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

This is from substr's manpage:

   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.

Now, the interesting part is that the result of substr can be used as an lvalue, and be assigned:

           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".

or you can use the replacement field:

           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().


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

replaces the last two characters of a string with F0.


Use the substr( ) function:

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

chop( ) and the related chomp( ) are really intended for removing line ending characters - newlines and so on.

I believe that substr( ) will be quicker than using a regular expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜