Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify the last two characters of a string in Perl

Tags:

string

perl

I am looking for 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?

like image 831
Shree Avatar asked Dec 07 '10 10:12

Shree


1 Answers

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().
like image 183
Nathan Fellman Avatar answered Oct 12 '22 00:10

Nathan Fellman