Why doesn't Perl support the normal [] operator to index a string?
Almost all major programming languages support this operator, especially the other two 'P': Python and PHP. Moreover, I do think it should be easy to implement this little syntax. Also, as the philosophy of the Perl programming language -- as lazy as we could, so why do we bother to use a function to index a string?
Will Perl 6 support this syntax?
Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and slicing.
=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {
Perl | index() Function This function returns the position of the first occurrence of given substring (or pattern) in a string (or text). We can specify start position. By default, it searches from the beginning(i.e. from index zero).
'ne' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise not equal to the string to its right. Syntax: String1 ne String2. Returns: 1 if left argument is not equal to the right argument.
I like all the answers so far, but the real answer is, "because Larry wants it that way". Really. Larry came up with a set of idioms and tools that worked for him, and he shared that with us in the form of Perl. If you don't think the way Larry thinks, then there are plenty of other tools to use. We don't need the whole world using Perl... just the people who "get it" the way Larry does.
Using []
to index into a string is a side effect of the way many programming languages treat strings: as arrays of characters (or wide characters, in the case of Unicode). In Perl, strings are first-class entities. Perl provides a wealth of ways for working with whole strings as a single value. If you're trying to index into a string you're probably doing something wrong. (e.g. writing C in Perl rather than using Perl idioms.) For the cases where you really do need to index into a string, use substr
.
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