๐Ÿ“˜ Incrementing array elements in Perl 6

Increment each element in an array.

In Perl 6, there is no need to explicitly iterate over an array to apply some operation to each element. Use a hyper-operator:

@data>>++;

Let us try it on a small array:

my @data = 1..10;
@data>>++;
say @data; [2 3 4 5 6 7 8 9 10 11]

Theย >>++ operator is a hyper-operator that applies theย ++ operator to each element of the array. As theย ++ operator modifies the element, the wholeย @data array is also modified after the operation.

Alternatively, one of the following forms may be used:

@data <<+=>> 1;
@data >>+=>> 1;

These constructions take every element of the array and perform theย += 1 operation on it.

Notice that if you omit theย = sign in the last examples, the original data is not modified.

my @data = 1..10;
my @new-data = @data >>+>> 1;
say @data;ย ย ย ย ย #ย [1 2 3 4 5 6 7 8 9 10]
say @new-data;ย #ย [2 3 4 5 6 7 8 9 10 11]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s