1 Replies - 389 Views - Last Post: 24 August 2016 - 10:21 AM

#1 tonyal  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 85
  • Joined: 23-September 14

Sorting from file

Posted 23 August 2016 - 05:04 PM

Hello. I'm making a program for a phone book, and I would like to be able to sort by last name alphabetically from a file. I've tried several different things following examples such as making keys, mapping, subhash, and other things I didn't get - with many people saying their way is better/easier/faster. I just want something simple and easy to understand for a beginner. My file consists of entries such as:
John:Doe:FL:Brother:2192204999

I need to sort by last name alphabetically and display the name and relationship. So far I have:
use warnings;

my ($first, $last, $state, $relationship, $phone, $key, $duphash);

open (my $Entries, "<", "FamilyAndFriends.dat") or die "Can't open file!";
while (my $record=<$Entries>){
    ($first, $last, $state, $relationship, $phone) = split /://>, $record;
    sort $last; //this is the last I tried before I gave up
    print "$last, $first, $relationship\n";
}

close $Entries;
print "\n";



If anyone could help I'd be very grateful! Thanks in advanced. :punk:

Is This A Good Question/Topic? 0
  • +

Replies To: Sorting from file

#2 tonyal  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 85
  • Joined: 23-September 14

Re: Sorting from file

Posted 24 August 2016 - 10:21 AM

Figured it out. In case anyone one finds this post looking for an answer for a similar problem, here's the code: (btw, I decided to join the first and last name in the .dat file instead of separating them like I did in the previous post.)

use warnings;

my ($name, $state, $relationship, $phone);

open ($fh, "<", "FamilyAndFriends.dat") or die "Can't open file!";
while (<$fh>){
    ($name, $state, $relationship, $phone) = split (":");
    ($first, $last) = split(/ /, $name);
    $duphash{$last,", ", $first, ":",$state, ":", $relationship}=$_;
}
    foreach $key (sort keys %duphash) {
        print "$key\n";
    }
close $fh;



I don't know if it's the most efficient way to do it - but it works! :)/>

This post has been edited by tonyal: 24 August 2016 - 10:23 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1