简体   繁体   中英

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.

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 } @_));
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM