← Back to Perl Course | Chapter 3: Strings | Lesson 4 of 7

length, substr and index

You can measure a string, cut pieces out of it and find where a piece begins.

In this page:

  1. length, substr and index

length, substr and index

length returns the number of characters, substr extracts or replaces part of a string, and index and rindex find the position of a substring. Positions start at 0, and index returns -1 when nothing is found. substr can also be assigned to, or given a fourth argument, to replace part of the string.

Note: A negative offset in substr counts from the end of the string.

Example: length, substr and index

perl
use strict;
use warnings;

my $s = "Hello, Perl world";
print "length: ", length($s), "\n";
print "substr: ", substr($s, 7, 4), "\n";
print "from end: ", substr($s, -5), "\n";
print "index of 'Perl': ", index($s, "Perl"), "\n";
print "index of 'xyz': ", index($s, "xyz"), "\n";
print "rindex of 'o': ", rindex($s, "o"), "\n";
substr($s, 0, 5) = "Howdy";
print "after assignment: $s\n";
my $removed = substr($s, 7, 4, "PERL");
print "removed '$removed', now: $s\n";

# Output:
# length: 17
# substr: Perl
# from end: world
# index of 'Perl': 7
# index of 'xyz': -1
# rindex of 'o': 13
# after assignment: Howdy, Perl world
# removed 'Perl', now: Howdy, PERL world
Common Mistakes
  1. Expecting index to return 1 for a match at the start
  2. Forgetting that index returns -1 when there is no match
  3. Assuming substr with a replacement returns the new string instead of the removed part
Chapter Summary
  • length counts characters
  • substr(str, offset, length) extracts text
  • index and rindex return positions or -1
  • substr can replace text
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.