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
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
:
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:
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.