我有一个包含数值的字符串。我想以相反的顺序显示数值。
不起作用的想法是使用内置的反向功能:
my $j = "12,11,10,9";
my $k = reverse($j);
print $k;
但该代码输出:
9,01,11,21
我们想要的时候:
9,10,11,12
答案 0 :(得分:11)
简明版:
my $j = "12,11,10,9";
print join ",", reverse split /,/, $j;
括号版本:
my $j = "12,11,10,9";
print(join(",", reverse(split(/,/, $j))));
如果我稍微分解一下:
my $j = "12,11,10,9";
my @j = split /,/, $j;
print join ",", reverse @j;
<强>输出强>
9,10,11,12
注意强>
perldoc -f reverse
答案 1 :(得分:3)
将字符串放入数组中,然后反转数组输出。 你只是简单地翻转完整的字符串。
@j_array = split(/,/, $j);
答案 2 :(得分:0)
由于您未提供有关输入来源的任何信息,因此常见 reverse()
答案的替代方法是发出sort
:
my $j = "12,11,10,9";
my $k = join ',' , sort {$a <=> $b} split /,/ , $j;
print $j, "\n";
print $k;
同样的事情分解为更多行:
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;