【问题标题】:Modify the last two characters of a string in Perl在 Perl 中修改字符串的最后两个字符
【发布时间】:2011-05-21 12:31:30
【问题描述】:

我正在寻找解决问题的方法:

我有 20 个字符长的 NSAP 地址:

39250F800000000000000100011921680030081D

我现在必须用F0 替换这个字符串的最后两个字符,最后的字符串应该是这样的:

39250F80000000000000010001192168003008F0

我当前的实现去掉了最后两个字符并将F0 附加到它:

my $nsap = "39250F800000000000000100011921680030081D";

chop($nsap);

chop($nsap);

$nsap = $nsap."F0";

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: perl string


    【解决方案1】:

    你可以使用substr:

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

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

    或者你可以使用一个简单的正则表达式:

    $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 的结果可以用作左值,并被赋值:

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

    【讨论】:

      【解决方案2】:
      $nsap =~ s/..$/F0/;
      

      将字符串的最后两个字符替换为F0

      【讨论】:

        【解决方案3】:

        使用substr( )函数:

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

        chop( ) 和相关的 chomp( ) 真正用于删除行尾字符 - 换行符等。

        我相信 substr( ) 会比使用正则表达式更快。

        【讨论】:

          猜你喜欢
          • 2012-05-17
          • 2011-04-04
          • 1970-01-01
          • 2017-02-22
          • 1970-01-01
          • 2014-08-06
          • 2016-01-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多