Home
FREE Newsletter
Perl How To
Perl Books
Perl Basics
Perl Editors
Perl Modules
Perl Database
Net Programming
Sitemap
About Me
Contact Me
Blog
 

Perl index Function



NEW!!!

Check my new resource:    Perl How To Tutorial eBooks



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:

index STR,SUBSTR,POSITION 
index STR,SUBSTR

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.


Check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.



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



Subscribe now to my FREE newsletter
(regarding tips and tricks to manipulate multidimensional
arrays and hashes in Perl)

and you'll receive a link to download for FREE my Perl chomp Function Tutorial eBook (a $7.50 value), it's a bonus for you and I hope you'll enjoy it. You can see its Table of Contents here (if you subscribe to my free newsletter, you don't have to pay for this eBook or use your paypal account).


Don't forget to check my new How To Tutorial eBooks (PDF format):

to see a lot of fully commented examples that help you use the Perl statements and the Perl buit-in functions in your scripts.





NEW!!!

Do you want more information about the basic Perl topics?

Check my new "Perl How To" Tutorial eBooks page where I'll answer the most frequent questions regarding some topics :


Perl How To Tutorial eBooks


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
        Array Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        grep
        hex
        index
        join
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        substr
        uc
        undef
        unshift

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!


footer for perl index page