📜 ⬆️ ⬇️

Feed operators in Perl 6

Perl 5 programmers came across this structure in code:

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


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

In Perl 6, data streams are transmitted directly through the feeding operator. The following example can be written in this form in Perl 6:
 my @new <== sort { ... } <== map { ... } <== grep { ... } <== @original; 

')
The principle of TMTOWTDI has not gone anywhere. The same can be written almost the same as it was in Perl 5:

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


The only difference is commas.

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

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

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


It works in the same way 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 the code:

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

Source: https://habr.com/ru/post/253701/


All Articles