Perl index Function

This short Perl index Tutorial will show you how to use this function in order to find a substring within another bigger string. I’ll give you several snippet code examples what I consider more important in order to highlight the topic and help you find out how to work with it. You can use the regular expression to match the first instance of a substring but this function may be faster and easier to understand.

Let’s begin with the syntax forms of this function:


where the argument parameters have the follow significance:
  • STR - the string you are searching
  • SUBSTR - the substring whose position you want to locate or to search for
  • POSITION – the position in the string from where you want to start the searching or the number of characters to skip over before searching for the substring
This function will return -1 if the substring will not be found or the position of the first occurrence of the substring, otherwise. Please remember that the first character of a string has the position 0, the next 1, and so on. If you don’t supply the third argument, i.e POSITION, that means that the Perl index function will search for your substring beginning with the first character of the string.

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

Like other Perl functions, you can use or omit the parentheses, as you like. See below some simple examples about how to use it in scripts:

my $someText = "Learning Perl Language";
my $found = index $someText, "Perl";
my $found1 = index($someText, "perl", 5);
print "\$found = $found,\$found1 = $found1\n";
# it prints $found = 9,$found1 = - 1

In the second line, the Perl index function will search the substring "Perl" in the scalar string $someText and it will return 9. In the third line, the index function will start searching from the sixth character of the $someText string, but this time it will return -1. That happens because the index function is case sensitive, but it’s easy to rewrite this code line using Perl uc (uppercase) function in order to find the substring case insensitive:

my $found1 = index(uc $someText, "PERL", 5);
print "\$found1 = $found1\n";
# it prints $found1 = 9

This time, the index function will return the position 9, that meaning the substring was found.

Remember that Perl index function returns -1 if it doesn’t succeed; if you want to use it in a conditional test, you must test if the returning value is greater or equal to 0 for success:

if((my $pos = index($someText, "Perl")) >= 0)
  print "The text was located at the position $pos\n";

Or you can replace the first line of the code above with:

if(($pos = index($someText, "Perl")) > -1)

and the result produced by running the code will be the same.

If you want to find out if a substring matches a bigger string and you don’t care about the substring position within the string, you can use a single line of code, like in the following example:

print "Found it!\n" if(index($someText,"Perl")>-1);

How to find all the occurrences of a substring in a string

You already know how to use Perl index function to locate the first occurrence of substring in a string. Now we want to find the positions of all the occurrences of a substring within a string, by using the index function.

See the following example:

# initialize the original string
my $input = "Perl index, Perl chop, Perl hex";
my $pos = 0;

my @positions = ();

while (1) {
  $pos = index(lc $input, "perl", $pos);
  last if($pos < 0);
  push(@positions, $pos++);

if (scalar (@positions) > 0) {
  print "substring found at positions: ", "@positions\n";
} else {
  print "substring not found\n";

Now I give a short description of this code. We initialize the scalar string $input and we intend to search for the substring "Perl" within this string. We use the Perl index function to do this and a while loop for iteration through the $input string characters.

If there will be a match of the substring in the scalar $input string, the index function will return the position of that occurrence in the scalar variable $pos, which next is added to @positions array by using Perl push function.

The loop will end when the index function will return a value less than zero – no occurrence was found. In order lo leave the while loop, we use the loop control keyword last.

Finally, we print @positions array which will display all the occurrences of the substring "Perl" in the $input string. Please note the using of Perl lc (lowercase) function in order to make our search case insensitive.

Running this snippet code will produce the following result:

substring found at positions: 0 12 23

Removing leading or trailing spaces in index function context

In the searching process using Perl index function, we can remove the leading and trailing spaces from the string where we search. Perl has not a build in trim function (like PHP) but we can simulate it by creating a subroutine trim with the help of regular expressions. See the next snippet code:

my $input = '    Perl functions: trim, index';
my $substr = 'functions';
print "position without trim: ", index($input,$substr), "\n";
print "position with trim: ", index(trim($input),$substr), "\n";

# Declare the trim subroutine
sub trim
  my $string = shift;
  $string =~ s/^\s+//;            
  $string =~ s/\s+$//; 
  return $string;         

In this example we print first the position of the $substr in the $input string and hence the position of the same substring after removing whitespaces from $input string. We get the output:

position without trim: 9
position with trim: 5

(the $input string value has 4 spaces before Perl word – you can’t count them on the screen!)

If you want to search for the last occurrence of a substring in a string, you need to use the built-in Perl rindex() function.

If you want to download the Perl index script with all the above examples included, please click here: Script download


Through these exercises you have the opportunity to try yourself to write some script code where you can use the Perl index function. These exercises are completely covered in my Perl "Perl Scalar and String Functions - How To Tutorial" where I show you how to play with this important function in detail.

1. Give a short example where to check if a string is a substring of another. Use the string: "Learning Perl Language" and print a message to show if the string "perl" is contained in the initial string. The search must be case insensitive.
2. Give an example about how to use the index function to find the leftmost or the rightmost occurrence of a substring in a string.
3. Write a short script example where to count all the matches of a substring in a string.

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!

Check these how-to tutorial eBooks (PDF format):

Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        index (more)

return from Perl index Function to Perl Basics

Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!