๐Ÿ“˜ Reverse a string using Perl 6

๐Ÿ“˜ Reverse a string using Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Print a string in the reversed order from right to left.

Strings, or the objects of the Str class, have the flip method, which does the work:

my $string = 'Hello, World!';
say $string.flip;

This code prints the desired result:

!dlroW ,olleH

Theย flip routine may be called both as a method on a string and as a stand-alone function:

say flip 'Abcdef'; # fedcbA
say 'Word'.flip;   # droW

Donโ€™t forget thatย say can also be called as a method:

'Magic'.flip.say; # cigaM

In Perl 6, there is also theย reverse routine, but it cannot be applied directly to strings. It accepts lists, so a string first has to be converted to the list of characters, then reversed, and later joined again to a string.

Here is the code that works according to this description.

my $string = 'Hello, World!';
my $reversed = $string.split('').reverse().join('');
say $reversed; # !dlroW ,olleH

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code