[英]How to modify last two characters of a string depending on a condition using Perl
[英]Modify the last two characters of a string in Perl
我正在尋找問題的解決方案:
我有NSAP地址,長度為20個字符:
39250F800000000000000100011921680030081D
我現在必須用F0
替換此字符串的最后兩個字符,最終字符串應如下所示:
39250F80000000000000010001192168003008F0
我當前的實現會切掉最后兩個字符並將F0
追加到它:
my $nsap = "39250F800000000000000100011921680030081D";
chop($nsap);
chop($nsap);
$nsap = $nsap."F0";
有沒有更好的方法來實現這一目標?
你可以使用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().
$nsap =~ s/..$/F0/;
用F0
替換字符串的最后兩個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.