Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

To find out if a given char is in a string, you can use the 'index()' function.

'index()' takes as string, a substring and an offset (this last one is optional) as parameters and returns the position (starting in zero) where the substring is within the first string; if not found it returns -1. By default, 'index()' returns the first ocurrence found, if you want to find the occurrence 'n', you must use the 'offset' paramater.

If you just want to find out the total number of occurrences of a given char in a string, use the 'tr' operator, see below for an example. Please notice that the use of 'tr' is valid only when finding a single character, it doesn't work when trying to find a substring.

Examples:

- Find the first occurrence
my $string = "perlhowto.com";
my $position = index($string, "o");
die "'o' not found\n" if ( position < 0 );
print "'o' found at position: $position\n";

- Find all ocurrences
my $string = "perlhowto.com";
my offset = 0;
my position;
while ( 1 )
{
  $position = index($string, "o", $offset);
  last if ( $position < 0 );
 
  print "'o' found at position: $position\n";
  $offset++;
}

- Find the total number of occurrences
my $string = "perlhowto.com";
my $total = $string =~ tr/o/o/;
print "Total numbers of 'o' found: $total\n";