Perl 6 Programming/Meta Operators

From Wikibooks, open books for an open world
Jump to: navigation, search

Meta Operators[edit]

Operators do things to data. Meta operators do things to operators.

List Operators[edit]

Reduction Operators[edit]

Reduction operators act on a list and return a scalar value. They do this by applying the reduction operator between every pair of elements in the array:

my @nums = 1..5;
my $sum = [+] @nums     # 1 + 2 + 3 + 4 + 5

The [ ] square brackets turn any operator that normally acts on scalars into a reduction operator to perform that same operation on a list. Reductions can also be used with relational operators:

my $x = [<] @y;   # true if all elements of @y are in ascending order
my $z = [>] @y;   # true if all elements of @y are in descending order

Hyper Operators[edit]

Reduction operators apply an operator to all the elements of an array and reduces it to a single scalar value. A hyper operator distributes the operation over all the elements in the list and returns a list of all results. Hyperoperators are constructed using the special "french quotes" symbols: « and ». If your keyboard doesn't support these, you can use the ASCII symbols >> and << instead.

my @a = 1..5;
my @b = 6..10;
my @c = @a »*« @b;
# @c = 1*6, 2*7, 3*8, 4*9, 5*10

You can also use unary operators with hypers:

my @a = (2, 4, 6);
my @b = -« @a;  # (-2, -4, -6)

Unary hyperoperators always return an array that is exactly the same size as the list it is given. Infix hyperoperators have different behavior depending on the sizes of its operands.

@a »+« @b;   # @a and @b MUST be the same size
@a «+« @b;   # @a can be smaller, will upgrade
@a »+» @b;   # @b can be smaller, will upgrade
@a «+» @b;   # Either can be smaller, Perl will Do What You Mean

Pointing the hyper symbols in different directions affects how Perl 6 treats the elements. On the sharp side, it extends the array to be as long as the one on the dull side. If both sides are sharp, it will extend whichever is smaller.

Hypers can also be used with assignment operators:

@x »+=« @y  # Same as @x = @x »+« @y

Cross Operators[edit]

The cross is a capital X symbol. As an operator, the cross returns a list of all possible lists made by combining the elements of it's operands:

my @a = 1, 2;
my @b = 3, 4;
my @c = @a X @b;  # (1,3), (1,4), (2,3), (2,4)

The cross can also be used as a meta operator, applying the operator it's modifying against every possible combination of elements from each operand:

my @a = 1, 2;
my @b = 3, 4;
my @c = @a X+ @b; # 1+3, 1+4, 2+3, 2+4