11

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?

4
  • 2
    It's not a feature. It's just syntax. Nov 2, 2009 at 16:13
  • 4
    There's nothing 'normal' about []. Not only that but [] may or may not be implemented as a function despite it's syntax (for example, in Ruby [] is actually a method).
    – rfunduk
    Nov 2, 2009 at 19:26
  • 3
    Side note: There is no requirement for Perl, Python, and PHP to share any features or syntax whatsoever. Those three languages have very different syntax, very different semantics, and very different design goals. If you expect them to be the same, then you are in for a major disappointment. (For example, in Haskell, the operator to extract the nth character from a string, or the nth item from any list, is $$. No one complains that Haskell doesn't use [] for that purpose...) Nov 2, 2009 at 22:41
  • @Daniel: Not quite correct, Haskell uses !!. For further examples: SML uses String.sub, Caml uses String.get (or .[]), J uses {~, XSLT uses substring, and Java uses .charAt().
    – ephemient
    Nov 3, 2009 at 1:32

7 Answers 7

44

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.

1
  • Yes, but what was Larry's rationale? Maybe you have some insight? Oct 15, 2017 at 16:17
23

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.

1
  • 5
    That a string is a first-class entity (as opposed to a simple array of characters) doesn't mean it can't be treated syntactically as an array. See Java, C#, and Delphi, for instance. Nov 2, 2009 at 20:48
18

Do you want to index by bytes, characters, or graphemes?

This is why in Perl 6 length is "banned", Instead you use one of the following:

  • bytes
    Exactly one byte at a time
  • chars
    Depending on the source text this can be a single byte, or several bytes.
  • graphs
    This is similar to chars, but combines multiple "combining" characters together.

If you really want it you can do something similar, using split.

( split '', $str )[$index];

It is probably better to just use substr though.

substr $str, $index, 1;
3
  • I'd have written (split //, $str)[$index] as that avoids building an unnecessary anonymous list, but both look kinda odd, don't they? substr($str, $index, 1) (or $str.substr($index, 1), in Perl 6) is probably the best, readability-wise.
    – ephemient
    Nov 2, 2009 at 17:29
  • 1
    For those confused by the "split undef", split can take a regular expression in //-notation (e.g. split /foo/) or any expression that should be interpreted as a regular expression (e.g. split "fo"."o"). The undef is promoted to an empty string and compiled as a regular expression, producing the same result as split //, except with a "Use of uninitialized value" warning. (The other difference is perl having to try to compile the regular expression for each time the split is executed instead of just once.)
    – ysth
    Nov 2, 2009 at 19:21
  • I used split '', ... here instead of split //, ... because of problems with the code highlighter. Feb 3, 2012 at 21:07
12

Perl has a way to index a string with index or substr. It supports the operation. That it does it with another syntax shouldn't matter. There's a reason we have more than one programming language. :)

I wouldn't say that [] is a "normal" operator. I'm sure people can list many languages that don't do that either.

9
  • It would help to add a line that describes the "another syntax"
    – Murali VP
    Nov 2, 2009 at 17:17
  • There's something wickedly ironic about someone complaining about brian's answer being short on details :) I will edit brian's answer to include the syntax suggested in the comment below.
    – DVK
    Nov 2, 2009 at 17:40
  • ... BTW, the reason it's ironic is brian seems to be the most prolific editors of others' Perl Qs and As, adding clarifying details quite often.
    – DVK
    Nov 2, 2009 at 17:41
  • I rolled back the edit and linked to substr instead. There weren't more details because the question wasn't asking how to index a string but why Perl didn't use a particular syntax. Nov 2, 2009 at 18:09
  • 2
    By the way, good writing comes from good editing. Since the goal of SO is to provide good info via Google, I'm constantly editing my own answers. Nov 2, 2009 at 19:46
9

If you really want to treat scalars as objects, you can use autobox.

I don't use autobox, but this should work:

my $indexed = ('foo'->list)[1];

autobox has hooks for defining objects to use for wrapping various data types.

So, if you really, really want it, you should be able to use autobox to create your own string class that will allow code like this:

my $indexed = 'foo'->[3];

So, I think the answer to your question, "Why doesn't Perl have [] syntax for string indexing?" is "Nobody has wanted it enough to implement it."

As to Perl 6, I haven't followed closely enough to give an answer beyond, "If it isn't present and you really want it, you will be able to add it yourself."

2
  • 2
    It isn't present in Perl 6, but I think you should simply be able to define a multi method postcircumflex:<[ ]>(Str, Int) (though I can't check since Rakudo doesn't support it yet).
    – ephemient
    Nov 2, 2009 at 17:31
  • ephemient: you can do that in Raku (née Perl 6) but only for access (it'd be sub postcircumfix:<[ ]>(Str \a, Int \b) { a.substr: b, 1 }. The problem is that you'd need to return a proxy for allowing editable access, but even with the above sub, my $a = "abc"; $a[2] = 'C' Positional's AT-POS will take priority and fail. Mixins could make a Str indexable, and eventually via augment that could be enabled for all strings Dec 21, 2019 at 5:53
7

In Perl, strings are scalars and thus are not subscriptable by default. You can use functions like substr() or index() to access specific characters in a string.

Unless Perl 6 breaks with this concept by changing strings to an array of char's I don't think there will be any changes to this.

4
  • Well, in Perl 6, scalars are objects, so there could very well be a method that does the same thing. Nov 2, 2009 at 15:22
  • I'm open for changes as long as they don't break all existing stuff ;)
    – Heals
    Nov 2, 2009 at 16:11
  • It could probably be done with some magic using autobox and overriding the [] operator.
    – Ether
    Nov 2, 2009 at 17:06
  • ..and now I see that daotoad has written up a solution doing exactly that. :)
    – Ether
    Nov 2, 2009 at 17:07
7

What's the name of the string? It's scalar, so the sigil will obviously be $. The rest of it follows standard variable naming standards; let's say $abc.

my $abc = 'A string';

As sigils signify contexts of the expression, and are not a part of the name, we have a collision.

my $def = $abc[2];

is not the 3rd letter of the scalar $abc, but the third element from an array--sharing the same symbol (but with a different sigil) : @abc.

So that expression, which was probably designed early for script-like symbol resolution, already has a meaning assigned to it.

Of course, as Brad's answer points out, there can only be a meaning to that if we make implicit assumptions as to what makes a part of the string an "item" in the "list". The more encodings you have to use, the worse those default assumptions work.

You might find a syntax you prefer more using autobox:

$string->ch( 2 );

(You would have to write ch yourself.) But that is necessarily more verbose than simply putting bracket's onto strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.