1. Perl
  2. builtin functions
  3. here

index function - search for a string

You can use the index function to search for string.

In the first argument, specify the string to be searched, and in the second argument, specify the string you want to search. You can specify the search start index in the third argument. If omitted, the search will be performed from the beginning of the string. If found, that index is returned, otherwise -1 is returned.

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

Search for the string that appears the second time

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

The search start index can be specified in the third argument of index. In the first search, specify the index next to the found index.

Get all indexes of the searched string

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

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

If you want to handle Unicode such as using Japanese

In order for the index function to handle Japanese correctly, the string must be an decoded string. See the following articles for decoded the string.

Search by regular expression

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

# Use a regular expression to find out if Ken exists
my $message = "I'm Ken";
if ($message =~ /Ken/) {
  ...
}

Programming example using index function

This is an example to get the first index of the comma using the index function.

# Find out the first index of the comma
my $csv = 'aaa,bbb,ccc';
my $found_index = index($csv, ',');
print "$found_index\n";

This is an example of simple index function.

# 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 the string using the index function
my $word_love_pos_first = index($message, 'love');

# Search for the 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";

# Repeated search
{
  my @found_indexes = ();
  my $found_posision = -1;
    
  while (1) {
    $found_posision = index($message, 'love', $found_posision + 1);
    last if $found_posision == -1;
    push @found_indexes, $found_posision;
  }

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

Output result

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

Related Informatrion