Using Raku (formerly known as Perl_6)
raku -ne 'put .words.rotor(2).map(*.reverse);'
OR
raku -ne '.words.rotor(2).map(*.reverse).put;'
OR
raku -ne '.words.rotor(2)>>.reverse.put;'
Sample Input:
one two three four five six
apple banana cocoa dish fish nuts
Sample Output:
two one four three six five
banana apple dish cocoa nuts fish
Above are answers coded in Raku, a member of the Perl-family of programming languages. Briefly: raku
is invoked at the command line using the -ne
linewise non-autoprinting flag(s). When using either the -ne
or -pe
command line flags, each line loads into $_
, a.k.a. Raku's "topic variable" ($_
is also the "topic variable" in Perl). A leading .
dot is shorthand for $_.
signifying that the methods that follow are to be applied to $_
, the topic variable. Successive methods are chained together with the .
dot operator, each transforming the input data in turn.
Going through the methods: we see the linewise input is broken on whitespace into words
, then rotor
-ed together into pairs of words (i.e. an argument of 2
is supplied). The name of the rotor
function may be a bit obscure, but I'm guessing it is meant to signify that individual elements of a data object are cycled or rotor
-ed through and grouped/clustered together. After rotor
-ing, each pair is individually addressed using map
, and the reverse
function applied. Finally, the output in printed with put
.
Note, the code above (using rotor
defaults) will drop any "incomplete sets of elements" at the end. To retain "incomplete sets of elements" at the end, either change the rotor
call to add a True partial
parameter, or use batch
which means the same thing:
raku -ne 'put .words.rotor(2, partial => True).map(*.reverse);'
Which is the same as:
raku -ne 'put .words.rotor(2, :partial).map(*.reverse);'
Which is the same as:
raku -ne 'put .words.batch(2).map(*.reverse);'
https://raku.org