Feed Operators in Perl 6

Original author: perlpilot
  • Transfer
Perl 5 programmers have come across this structure in code:

    my @new = sort { ... } map { ... } grep { ... } @original;


Here the data goes from right to left, from the array @originalthat is fed to grep, which, in turn, feeds the data to map, and that to sort, and at the end all this is assigned to the array @new. Each of them takes a list as an argument.

In Perl 6, data streams are passed directly through the feed statement. The presented example can be written in this form in Perl 6:

    my @new <== sort { ... } <== map { ... } <== grep { ... } <== @original;


The TMTOWTDI principle has not gone anywhere. The same can be written in much the same way as it was in Perl 5:

    my @new = sort { ... }, map { ... }, grep { ... }, @original;


The difference is only in commas.

What does this operator give us? Reading the code, you do it from left to right. In Perl 5 code, you can read the example from left to right, and then it turns out that it works from right to left. Perl 6 introduced a syntax marker that clearly shows the direction of data flow.

To improve the readability of the code and turn the data stream in the right direction, from left to right, there is a special feeding operator:

    @original ==> grep { ... } ==> map { ... } ==> sort { ... }  ==> my @new;


This works exactly the same as the previous version, just the data goes from left to right. Here are some more examples of the actual use of this operator in code:

    my @random-nums = (1..100).pick(*);
    my @odds-squared <== sort() <== map { $_ ** 2 } <== grep { $_ % 2 } <== @random-nums;
    say ~@odds-squared;
    my @rakudo-people = ;
    @rakudo-people ==> grep { /at/ } ==> map { .ucfirst } ==> my @who-it's-at;
    say ~@who-it's-at;

Also popular now: