在perl中对数组进行排序并在一行中返回结果

Sorting an array in perl and returning the result in one line

我试图在 Perl 中对一个数组进行排序,从 Z 到 A,return 排序后的数组在一行中。

我正在做的是:

sub mainTexts {

    my @texts = ();

    print ("Enter text 1: ");
    my $text1 = <STDIN>;
    push @texts, $text1;
    print ("Enter text 2: ");
    my $text2 = <STDIN>;
    push @texts, $text2;
    print ("Enter text 3: ");
    my $text3 = <STDIN>;
    push @texts, $text3;

    my @sorted_texts = sort { lc($b) cmp lc($a) } @texts;

    print "Your texts are: ", @sorted_texts;


}

mainTexts();

这导致:

Your texts are: ZSAHS

FGDSJ

ABCNA

而我想要的结果是:

Your texts are: ZSAHS FGDSJ ABCNA

任何线索如何从上面的代码实现这一点?谢谢

来自 readline 运算符 (<>) 的输入通常会在行尾包含换行符,因此您需要将其传递给没有默认值的 chomp. Then, you can interpolate the array directly into the string rather than passing it as additional arguments to print. Interpolating an array separates each argument with $" which defaults to a space, while separate arguments to print are separated by $,,但是通常设置为换行符。

my @texts;

print ("Enter text 1: ");
chomp(my $text1 = <STDIN>);
push @texts, $text1;
print ("Enter text 2: ");
chomp(my $text2 = <STDIN>);
push @texts, $text2;
print ("Enter text 3: ");
chomp(my $text3 = <STDIN>);
push @texts, $text3;

my @sorted_texts = sort { lc($b) cmp lc($a) } @texts;

print "Your texts are: @sorted_texts\n";

由于 chomp 也可以对列表进行操作,因此您可以在读取所有输入后只添加一个 chomp 调用。

chomp(@texts);

你的$a和$b不是颠倒了吗? 操作行应该是:

my @sorted_texts = sort { lc($a) cmp lc($b) } @texts;