I am I am - 5 months ago 13
Perl Question

How do I reverse a string of numbers in Perl?

I have a string which contains numerical values. I want to display the numerical values in reverse order.

An idea that doesn't work is to use the built-in reverse function:

my $j = "12,11,10,9";
my $k = reverse($j);
print $k;


But that code outputs:

9,01,11,21


When we want:

9,10,11,12

Answer

Concise version:

my $j = "12,11,10,9";
print join ",", reverse split /,/, $j;

Parentheses version:

my $j = "12,11,10,9";
print(join(",", reverse(split(/,/, $j))));

If I decompose it a bit:

my $j = "12,11,10,9";
my @j = split /,/, $j;
print join ",", reverse @j;

OUTPUT

9,10,11,12

NOTE

  • See perldoc -f reverse