in reply to Function skips
There is no need to create an intermediate hash. Read the data, sort it, and then "funnel the lines" in to the various output files. Only one file needs to be open at once - this will vastly increase the speed of the code.
There are techniques to modify the sort order. But that should be a separate SOPW (Seeker of Perl Wisdom) question. The default sort order here looked "ok" to me.
There is no need to close FILE, when changing that file handle to a different location (the open() does that automatically). The last FILE will be closed with when the program exits.
#!/usr/bin/perl -w use strict; use constant DEBUG => 1; my @data = sort <DATA>; # bring all data into memory and sort # other techniques are possible if this # file is so big that this is not feasible my $current_first_letter = ''; foreach my $line (@data) { print "Processing $line" if DEBUG; # # skip entries not beginning with lower case a-z # my $this_first_letter; next unless ( ($this_first_letter) = $line =~ /^([a-z])/ ); # # Start a new file when we change first letters # if ($this_first_letter ne $current_first_letter) { my $filename = $this_first_letter . "_words.txt"; print "Creating New File...$filename...\n" if DEBUG; #this over-writes any existing file of the same name # open FILE, '>', $filename or die "can not open $filename $!"; $current_first_letter = $this_first_letter; } # # write to the current file # print "....adding $line"; print FILE $line; } =prints -- look in the output files for the rest.. -- set DEBUG =>0 to supress this ouput Processing Bob/person Processing d/some fictional animal Creating New File...d_words.txt... ....adding d/some fictional animal #a sort test case # Processing dog/pet ....adding dog/pet Processing doggie/also a pet ....adding doggie/also a pet Processing horse/an animal Creating New File...h_words.txt... ....adding horse/an animal =cut __DATA__ dog/pet d/some fictional animal horse/an animal doggie/also a pet Bob/person
|
|---|