tavalendo
tavalendo

Reputation: 877

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

I am trying to sort an array in Perl from Z to A and return the sorted array in one line.

What I am doing is:

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();

This results in:

Your texts are: ZSAHS

FGDSJ

ABCNA

While the result I want is:

Your texts are: ZSAHS FGDSJ ABCNA

Any clue how to achieve this from the code above? Thanks.

Upvotes: 2

Views: 428

Answers (2)

Bruce Van Allen
Bruce Van Allen

Reputation: 177

Isn't the main answer that you have $a and $b reversed? The operative line should be:

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

Upvotes: 0

Grinnz
Grinnz

Reputation: 9231

Input from the readline operator (<>) will generally contain the newline at the end of the line, so you need to pass it to 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 $, which doesn't have a default, but is commonly set to a newline.

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";

Since chomp can also operate on a list, you can just add one chomp call instead after reading all the input.

chomp(@texts);

Upvotes: 4

Related Questions