$RESULT = substr(EXPR, OFFSET, LENGTH);
Perl's
substr() function takes a string and returns a specified portion of it that begins at
OFFSET and extending for
LENGTH number of characters.
substr is short for sub-string. Be aware that the OFFSET number starts at
zero on the first character.
$sentence = "The quick brown fox jumps over the lazy dog.";
$chunk = substr($sentence, 4, 5);
In the above example, the
substr function carves out the word 'quick' from
$sentence and puts it into the
$chunk string. If you count up (starting at zero, remember), you'll see that the
q is in place 4 and extends for 5 characters (
OFFSET and
LENGTH).
There is an optional
REPLACEMENT value that you can use to replace the sub-string even as you carve it out. To do this, simply pass the string in the forth argument like so:
$sentence = "The quick brown fox jumps over the lazy dog.";
$chunk = substr($sentence, 4, 5, 'slow');
In this example,
$chunk is still set to 'quick', but the value of
$sentence is changed to 'The slow brown fox jumps over the lazy dog.'
More Perl Quick Tips