根据位置替换字符串中的字符
Replacing a character in a string based on position
我正在尝试使用 Perl 根据其位置替换字符串中的字符。
这是我所做的:
my ($pos, $rep) = @ARGV;
print ("Give me the string: ");
chomp(my $string = <STDIN>);
print ("The modified string is ", substr($seq, $pos, 1, $rep),"\n");
当我在终端运行:
perl myprogram.pl 4 B
Give me the string: eeeeee
The modified string is e
我想要的输出是:eeeeBe
知道哪里出了问题吗?
An alternative to using substr
as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice
.
(强调我的。)
换句话说,substr
总是returns原始字符串的子字符串。如果要打印修改后的字符串,分两步进行:
substr $seq, $pos, 1, $rep;
# or alternatively:
# substr($seq, $pos, 1) = $rep;
print "The modified string is $seq\n";
我正在尝试使用 Perl 根据其位置替换字符串中的字符。
这是我所做的:
my ($pos, $rep) = @ARGV;
print ("Give me the string: ");
chomp(my $string = <STDIN>);
print ("The modified string is ", substr($seq, $pos, 1, $rep),"\n");
当我在终端运行:
perl myprogram.pl 4 B
Give me the string: eeeeee
The modified string is e
我想要的输出是:eeeeBe
知道哪里出了问题吗?
An alternative to using
substr
as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can withsplice
.
(强调我的。)
换句话说,substr
总是returns原始字符串的子字符串。如果要打印修改后的字符串,分两步进行:
substr $seq, $pos, 1, $rep;
# or alternatively:
# substr($seq, $pos, 1) = $rep;
print "The modified string is $seq\n";