2010-12-07 11 views
8

में एक स्ट्रिंग के अंतिम दो पात्रों को संशोधित मैं एक समस्या के समाधान के लिए देख रहा हूँ:पर्ल

39250F800000000000000100011921680030081D 

मैं अब बदलने के लिए: मैं एनएसएपी पते जो 20 वर्ण लंबा है है

F0 के साथ इस स्ट्रिंग और अंतिम स्ट्रिंग के अंतिम दो पात्रों दिखना चाहिए:

39250F80000000000000010001192168003008F0 

मेरे वर्तमान कार्यान्वयन पिछले दो पात्रों कांट-छांट और 012,364 संलग्न कर देता हैइसे:

my $nsap = "39250F800000000000000100011921680030081D"; 

chop($nsap); 

chop($nsap); 

$nsap = $nsap."F0"; 

क्या इसे पूरा करने का कोई बेहतर तरीका है?

उत्तर

18

आप substr उपयोग कर सकते हैं:

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

या

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

या आप एक सरल regex का उपयोग कर सकते हैं:

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

यह 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. 

अब, दिलचस्प बात यह है कि 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() नियमित अभिव्यक्ति का उपयोग करने से तेज़ होगा।