Perl Programming/Keywords/substr

Previous: sub Keywords Next: symlink

The substr keyword edit

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 edit

  substr EXPRESSION, OFFSET, LENGTH, REPLACEMENT
  substr EXPRESSION, OFFSET, LENGTH
  substr EXPRESSION, OFFSET

Examples edit

  The code
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.


Previous: sub Keywords Next: symlink