Skip navigation.
Your source for Perl tips, howto's, faq and tutorials

find the occurrences of a given char in a string

( 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.

length: return the number of characters of a string

( categories: | )

Use the length function to get the number of characters of a string. Special characters, such as new line (\n) and carriage return (\r) are also included in the length calculation.

Please notice that this function works on scalar variables, you can't use it to get the number of elements of an array or a hash.


$line = "perl test line\n";
print "\$line has " . length($line) . " lines\n";

Syndicate content