πŸ“˜ Reverse a string using Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s