Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Perl support the normal [] operator to index a string?

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?

like image 377
Jichao Avatar asked Nov 02 '09 15:11

Jichao


People also ask

Can we use indexing in string?

Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and slicing.

What does =~ mean in Perl?

=~ 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/) {

What does Index function do in Perl?

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

What is NE in Perl?

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


2 Answers

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.

like image 80
Randal Schwartz Avatar answered Oct 13 '22 05:10

Randal Schwartz


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.

like image 31
Michael Carman Avatar answered Oct 13 '22 03:10

Michael Carman