πŸ“˜ How to reverse a list in Perl 6

Print the given list in reverse order.

Start with an array of integer numbers.

my @a = (10, 20, 30, 40, 50);

To reverse the array, call the reversemethod on it.

say @a.reverse;

This line prints the required result:

(50 40 30 20 10)

Notice that the initial array stays unchanged. The reversemethod creates a new sequence and returns it.

The same method works with other types of data that can be converted to a sequence, for example, ranges.

Print a range in reversed order:

my $range = 10..15;
say $range;
say $range.reverse;

Again, the original range is not changed, and the returned value is not a range but a sequence. Compare the results of printing an original value ofΒ $range with what theΒ reverse method returns:

10..15
(15 14 13 12 11 10)

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