I am I am - 1 year ago 77
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:


When we want:


Answer Source

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;




  • See perldoc -f reverse
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download