1. Home
  2. Computing & Technology
  3. Perl

Perl array substr() function - Quick Tutorial

How to use the substr() function

By Kirk Brown, About.com

$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

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl substr function reference - learn how to use Perl's substr() function in this quick tutorial.

©2008 About.com, a part of The New York Times Company.

All rights reserved.