Go to the first, previous, next, last section, table of contents.


Replacing a Subsequence of a List or String

The subrange assigment replaces a specified subsequence of a list or string with a supplied subsequence. The allowed forms are:

variable[start-index-expr..end-index-expr] = result-expr
object-expr.name[start-index-expr..end-index-expr] = result-expr
object-expr.(name-expr)[start-index-expr..end-index-expr] = result-expr
$name[start-index-expr..end-index-expr] = result-expr

As with indexed assigments, the first form writes into a variable, and the last three forms write into a property. The same errors (E_TYPE, E_INVIND, E_PROPNF and E_PERM for lack of read/write permission on the property) may be raised. If variable does not yet have a value (i.e., it has never been assigned to), E_VARNF will be raised. As before, the $ expression can be used in either start-index-expr or end-index-expr, meaning the length of the original value of the expression just before the [...] part.

If start-index-expr or end-index-expr is not an integer, if the value of variable or the property is not a list or string, or result-expr is not the same type as variable or the property, E_TYPE is raised. E_RANGE is raised if end-index-expr is less than zero or if start-index-expr is greater than the length of the list or string plus one. Note: the length of result-expr does not need to be the same as the length of the specified range.

In precise terms, the subrange assigment

v[start..end] = value

is equivalent to

v = {@v[1..start - 1], @value, @v[end + 1..$]}

if v is a list and to

v = v[1..start - 1] + value + v[end + 1..$]

if v is a string.

The assigment expression itself returns the value of result-expr. For the following examples, assume that l initially contains the list {1, 2, 3} and that s initially contains the string "foobar":

l[5..6] = {7, 8}       error-->   E_RANGE
l[2..3] = 4            error-->   E_TYPE
l[#2..3] = {7}         error-->   E_TYPE
s[2..3] = {6}          error-->   E_TYPE
l[2..3] = {6, 7, 8, 9} =>   {6, 7, 8, 9}
l                      =>   {1, 6, 7, 8, 9}
l[2..1] = {10, "foo"}  =>   {10, "foo"}
l                      =>   {1, 10, "foo", 6, 7, 8, 9}
l[3][2..$] = "u"       =>   "u"
l                      =>   {1, 10, "fu", 6, 7, 8, 9}
s[7..12] = "baz"       =>   "baz"
s                      =>   "foobarbaz"
s[1..3] = "fu"         =>   "fu"
s                      =>   "fubarbaz"
s[1..0] = "test"       =>   "test"
s                      =>   "testfubarbaz"


Go to the first, previous, next, last section, table of contents.