Perl 编程/关键字/substr
外观
Thesubstr命令从EXPRESSION中提取并返回子字符串,其中第一个字符位于OFFSET 0处。如果OFFSET为负数,则从字符串末尾开始计数。如果LENGTH为负数,则从字符串末尾保留这么多字符。
substr也可以用作左值,如果EXPRESSION也是左值。通过分配大于或小于LENGTH的字符串,字符串将分别增长或缩小以容纳它。
如果OFFSET和LENGTH指定的子字符串部分位于字符串外部,则仅返回字符串内的部分。如果它超出了两端,则返回 undef,如果它是一个左值,则会抛出异常。
substr EXPRESSION, OFFSET, LENGTH, REPLACEMENT
substr EXPRESSION, OFFSET, LENGTH
substr EXPRESSION, OFFSET
代码
my $name = 'Anton';
print "name = \"", $name, "\"\n";
substr($name, 5) = 'io'; # $name is now "Antonio"
print "name = \"", $name, "\"\n";
my $null = substr $name, 7, 2; # returns "" w/o warning
print "null = \"", $null, "\"\n";
my $oops = substr $name, 8; # returns undefined with a warning
print "oops = \"", $oops, "\"\n";
substr($name, 8) = 'gap'; # raises an exception
print "name = \"", $name, "\"\n";
返回
name = "Anton" name = "Antonio" null = "" oops = "" substr outside of string at substr.pl line 13.