Loading ...
Sorry, an error occurred while loading the content.

RE: [PBML] Re: sort a file by a field

Expand Messages
  • Denny Malloy
    Yes I am familar with arrays and hashes. I never thought about doing it that way. THANKS for your help. Denny Malloy ... From: Damien Carbery
    Message 1 of 1 , Mar 1, 2001
    • 0 Attachment
      Yes I am familar with arrays and hashes. I never thought about doing it
      that way.
      THANKS for your help.

      Denny Malloy

      -----Original Message-----
      From: Damien Carbery [mailto:daymobrew@...]
      Sent: Thursday, March 01, 2001 12:55 PM
      To: perl-beginner@yahoogroups.com
      Subject: [PBML] Re: sort a file by a field


      Are you familar with split() and hashes?
      You could read in each line and place it all in a hash. Once you've
      finished reading the file you can sort the hash by social security
      number and print each line out.

      The script:
      #!/usr/local/bin/perl -w

      use strict;

      my ( %UnSorted, $SSN );
      if ( open( UNSORTED, "<list.txt" ) )
      {
      while( <UNSORTED> )
      {
      chomp;
      $SSN = ( split /,/ )[ 5 ]; # Get SSN.
      $UnSorted{ $SSN } = $_; # Store whole line.
      # Or replace the last two lines with:
      # $UnSorted{ ( split /,/ )[ 5 ] } = $_; # Store whole line.

      }
      close UNSORTED;

      open( SORTED, ">newlist.txt" );
      # The hash key is the SSN so sort by that.
      foreach ( sort keys %UnSorted )
      {
      print SORTED "$UnSorted{ $_ }\n"; # Print to file.
      }
      close SORTED;

      print "Sorted list in newlist.txt.\n";
      }
      else
      {
      print "Error opening file.";
      }


      --- In perl-beginner@y..., Denny Malloy <denny.malloy@n...> wrote:
      > Hi,
      >
      > Is there an easy way to sort a file by a field in that file using
      PERL?
      > I have an ASCII comma delimited file with name, address and social
      security
      > number. I need to sort this file by social security number only and
      write
      > it back out.
      >
      > Example of file:
      > name,address,city,state,zip,ssn
      >
      > THANKS for any input anyone might have!
      >
      > Denny Malloy





      Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
    Your message has been successfully submitted and would be delivered to recipients shortly.