Perl Sort on Text File

Hi,

I have a file of names and I want perl to do a sort on this file. How can I sort this list of names using perl? I'm thinking of a command like:

@sorted = sort { lc($a) cmp lc($b) } @not_sorted # alphabetical sort

The only thing I'm sort of unsure of is, how would I get the name in my text file into @sorted?

Also, would it be possible to use this perl code in the middle of a shell script? I think I remember someone telling me I could do something like this but I'm not sure of the tags I need to specify for this to work. Thanks!

Elt

in order to work your command, you have to get the contents of file in the array @not_sorted. So read the file as follows:

open (NAMES_FILE, "< /path/to/file")  or  die "Failed to read file : $! ";
my @not_sorted = <NAMES_FILE>;  # read entire file in the array
close (NAMES_FILE);

now using your statement you would get the sorted names in the @sorted array.
This would be a Perl script, so you will have to invoke it from your shell script. But if you want to access the sorted list in your shell script, then you will have to store it somewhere (in a file).
Alternatively, think of doing the sorting using shell commands and tools. This way, you need not invokde a diffeerent Perl script.

if it's in a shell script why not just use sort?

Cool thanks!

@bigearsbilly: I thought about that but I was told that the sort in shell does funny things and that perl would be more reliable. Maybe I'll try that and check out the results

Sorry one more question. I got the file sorted and did a

print @sorted;

to verify it. How do I save the array @sorted into a file? Not sure of the operator or if there even is an operator for that in PERL. Thanks!

Something like this,

each of the array contents should be flushed to the file

open(FILE, ">", "write" ) || die "unable to open file write <$!>";
  
  foreach(@sorted) {
    print FILE "$_";
  }
  
  close(FILE);

Cool, Thanks!