Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Perl6 have a method for checking substring matches?

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?

like image 815
Stefanus Avatar asked Mar 31 '18 20:03

Stefanus


People also ask

How do I check if a string is in a substring in Perl?

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.

How do you check if a pattern exists in a string in Perl?

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.


1 Answers

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.

like image 159
Brad Gilbert Avatar answered Oct 12 '22 04:10

Brad Gilbert