简体   繁体   中英

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

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

Put the string into an array and then reverse the array output. You are simply reversing the complete string as it stands.

@j_array = split(/,/, $j);

Since you did not give any information on the origination of inputs, an alternative to the common reverse() answers is to issue a sort :

http://codepad.org/q3dIkzO4

my $j = "12,11,10,9";
my $k = join ',' , sort {$a <=> $b} split /,/ , $j;

print $j, "\n";
print $k;

The same thing broken down into more lines:

http://codepad.org/pwTvg1c1

my $j = "12,11,10,9";        # Original string
my @k = split ',', $j;       # Breaking the numbers into an array
@k = sort {$a <=> $b} @k;    # Applying a sort (could use "reverse()" in its place)
my $k = join ',' , @k;       # Combine the numbers with a comma

print $j,"\n";
print $k;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM