user3462362
user3462362

Reputation: 3

Sort input text file and output file in ascending order (perl)

I am new to programming with perl and I am having issues with how to approach this problem in my assignment. It's pretty simple-- subroutine reads in an input text file where each line contains last name, first name, and score (in that order), separated from each other by a single blank:

Williams John 999
Desplat Alexandre 123
Zimmer Hans 234
Newman Thomas 637

etc. Output will look just like the input file, just that they are in order according to last name.

I was thinking that I should be using an associative array/hash? I can't use in perl's built in 'sort' function. If someone could explain/describe how I could implement a hash here, that would be excellent.

Upvotes: 0

Views: 480

Answers (1)

Lee Duhem
Lee Duhem

Reputation: 15121

Try this (revised version suggested by @Zaid, thank you):

perl -e 'print sort <>' data_file

If you cannot use Perl builtin sort, then you need to implement your own sort routine. For example:

sub mySort {
        return @_ if @_ <= 1;

        my $pivot = shift;

        return (mySort (grep { $_ le $pivot } @_),
                $pivot,
                mySort (grep { $_ gt $pivot } @_));
}

Upvotes: 2

Related Questions