2010-12-07 2 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 «s:

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 может быть использован в качестве Lvalue, и быть назначены:

  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() будет быстрее, чем использование регулярного выражения.

Смежные вопросы