< Perl Programming < Keywords
![](../../../I/Crystal_Clear_action_apply.png.webp)
The code
The substr keyword
The substr command extracts and returns a substring out of EXPRESSION, where the first character is at OFFSET 0. If OFFSET is negative, it starts to count from the end of the string. If LENGTH is negative, it leaves that much characters from the string's end.
substr can also be used as an lvalue, if EXPRESSION is also an lvalue. By an assignment larger or shorter than LENGTH, the string will grow or shrink respectively to accommodate it.
If OFFSET and LENGTH specify a substring partly outside the string, only the part within the string is returned. If it is beyond both ends, undef is returned, and an exception is raised, if it is an lvalue.
Syntax
substr EXPRESSION, OFFSET, LENGTH, REPLACEMENT
substr EXPRESSION, OFFSET, LENGTH
substr EXPRESSION, OFFSET
Examples
![](../../../I/Crystal_Clear_action_apply.png.webp)
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";
returns
name = "Anton" name = "Antonio" null = "" oops = "" substr outside of string at substr.pl line 13.
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.