www.webdeveloper.com
Results 1 to 2 of 2

Thread: Sorting a list?

Hybrid View

  1. #1
    Join Date
    Mar 2003
    Posts
    4

    Sorting a list?

    is it possible to display names from a plain txt file and sort them alphabetically by surname? or just alphabetically as they stand? They are stored in a text file like so:

    John Smith
    Joe Brown
    Ben Straw

    Thanks.

  2. #2
    Join Date
    Nov 2002
    Location
    NY, USA
    Posts
    731
    You can sort them however you wish, after a little manipulation. I might go about it like this:
    Code:
    use strict;
    use warnings FATAL => 'all';
    
    chomp(my @names = <DATA>);
    my %names;
    
    for (@names) {
        my($fn, $ln) = split;
        push @{$names{$ln}}, $fn;
    }
    
    undef @names;
    
    for my $ln (sort keys %names) {
        push @names, "$_ $ln" for sort @{$names{$ln}};
    }
    
    print join("\n", @names);
    
    __DATA__
    John Smith
    Joe Brown
    Ben Straw

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles