Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
Start on day 10 article
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| =head1 Day 10 - Feed operators | ||
|
|
||
| Anyone who has programmed in Perl 5 for a while has probably run across | ||
| or written code similar to this: | ||
|
|
||
| my @new = sort { ... } map { ... } grep { ... } @original; | ||
|
|
||
| In this construction, the data flows from the C<@original> array which | ||
| feeds into the C<grep>, and that, in turn, feeds into the C<map>, and | ||
| then into the C<sort>, and then finally, the result is assigned to the | ||
| C<@new> array. Because they each take a list as their final | ||
| parameter, simply by juxtposition, the data feeds from one operation | ||
| to the next. | ||
|
|
||
| Perl 6, on the other hand, makes this idea of data flowing from one | ||
| operation to another explicit by introducing the I<feed operator>. The | ||
| above Perl 5 code would be written like this in Perl 6: | ||
|
|
||
| my @new <== sort { ... } <== map { ... } <== grep { ... } <== @original; | ||
|
|
||
| So, what do we gain from this? Normally, when reading code, you read | ||
| from left to right. In the original Perl 5 code you would read from left | ||
| to right until you realize that you're dealing with constructions where | ||
| the direction of flow is right to left, then you jump to the end and | ||
| follow the processing in a right-to-left manner. In Perl 6 there is now | ||
| a prominent syntactic marker that clues you in to the leftward flowing | ||
| nature of the data. | ||
|
|
||
| Still, the right-to-left nature of this code is somewhat troublesome. | ||
| It may not seem so onerous if all of the code fits on one line as | ||
| above. But imagine if the blocks associated with C<grep>, C<map>, and | ||
| C<sort> were little longer. Finding the end of the statement could be a | ||
| bit annoying. | ||
|
|
||
| Luckily, Perl 6 has another feed operator that allows you to write the | ||
| same statement in a left-to-right fashion: | ||
|
|
||
| @original ==> grep { ... } ==> map { ... } ==> sort { ... } ==> my @new; | ||
|
|
||
|
|