2010-12-07 28 views
8

Busco a una solución a un problema:Modificar los dos últimos caracteres de una cadena en Perl

tengo la dirección NSAP que es de 20 caracteres de longitud:

39250F800000000000000100011921680030081D 

ahora tengo que sustituir los dos últimos caracteres de esta cadena con F0 y la cadena final debe ser similar:

39250F80000000000000010001192168003008F0 

Mi implementación actual chuletas de los dos últimos caracteres y anexa F0 a él:

my $nsap = "39250F800000000000000100011921680030081D"; 

chop($nsap); 

chop($nsap); 

$nsap = $nsap."F0"; 

¿Hay una manera mejor de lograr esto?

Respuesta

18

Puede utilizar substr:

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

o

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

O puede usar una expresión regular simple:

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

Esto es de página de manual 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. 

Ahora, lo interesante es que el resultado de substr se puede utilizar como un valor-I, y se asignará:

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

o puede utilizar el reemplazo campo:

  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/; 

sustituye a los dos últimos caracteres de una cadena con F0.

5

Utilice la función substr():

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

chop() y la chomp relacionada() están pensadas para eliminar caracteres de final de línea - líneas nuevas, etc.

Creo que substr() será más rápido que usar una expresión regular.

Cuestiones relacionadas