Perl Newbies

  1. Perl
  2. Functions
  3. here

index function - Search for string

index function search for string.

my $pos = index($target, $str);

Specify string in the first argument, and specify string searched for in the second argument. You can specify searching start position in the third argument. If omitted, the search starts from the beginning of the string. If string is found, the position is returned. If string is not found, -1 is returned.

Search for string that appears the second time

my $word_love_pos_second = index($message, 'love', $word_love_pos_first + 1);

You can specify start position in the third argument of index function. Specify next position you get by first index function.

Get all positions of searched string

{
  my @found_positions = ();
  my $found_posision = -1;
    
  while (1) { 
    $found_posision = index($message, 'love', $found_posision + 1);
    last if $found_posision == -1;
    push @found_positions, $found_posision;
  }
    
  print "Found: " . join(', ', @found_positions) . "\n";
}

In while statement, repeat index function until return value is -1.

If you want to handle Japanese

To handle Multibyte string such as Japanese correctly with the index function, the string must be decoded string. For decoded string, see the following article.

Search by regular expression

You can also search for a string using regular expressions. If you want to specify the target string instead of the character position, use a regular expression.

# Check "Ken" existance using regular expression
my $message = "I'm Ken";
if ($message =~ /Ken/) {
  ...
}

index function programming example

This is a example to find the first position of comma using index function.

# Find the first position of the comma
my $csv = 'aaa,bbb,ccc';
my $pos = index($csv, ',');

if true block is processed only when the string is found.

# Process only if the string is found
my $string = "I'm Ken";
my $search = 'Ken';

if (index($string, $search) != -1) {
  print "Found\n";
}

Other examples.

use strict;
use warnings;

my $message = "love love love.";

# Search for string "love" using index function
my $word_love_pos_first = index($message, 'love');

# Search for second "love"
my $word_love_pos_second = index($message, 'love', $word_love_pos_first + 1);

print "First: $word_love_pos_first, Second: $word_love_pos_second\n";

# Search for string repeatedly
{
  my @found_positions = ();
  my $found_posision = -1;
    
  while (1) { 
    $found_posision = index($message, 'love', $found_posision + 1);
    last if $found_posision == -1;
    push @found_positions, $found_posision;
  }

  print "Found: " . join(', ', @found_positions) . "\n";
}

Output:

First: 0, Second: 5
Found: 0, 5, 10
Menu