How can one check for substring matches in Perl?
The index
method returns an Int
:
"abc".index("b")
1
Using defined
, the result can be turned into a Bool
:
"abc".index("b").defined
True
Is this the idiomatic way or is there another method that returns a Bool
?
To search for a substring inside a string, you use index() and rindex() functions. The index() function searches for a substring inside a string from a specified position and returns the position of the first occurrence of the substring in the searched string.
The Match Operators Perl defines special operators that test whether a particular pattern appears in a character string. The result of the =~ operation is one of the following: A nonzero value, or true, if the pattern is found in the string. 0, or false, if the pattern is not matched.
The method is .contains
.
say 'abc'.contains('b'); # True
There is also .starts-with
and .ends-with
.
say 'abc'.starts-with('c'); # False
say 'abc'.starts-with('a'); # True
say 'abc.txt'.ends-with('.txt') # True
You can look at the Str docs for more methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With