in reply to Function skips
Also $line should be passed as a parameter to writeFiles - try to minimize the number of global variables.
This code will work, but opening a file is "expensive". Further work could result in only opening each file one time.
Also if you had enabled warnings and strictures, you would see that this line
for ($i; $i<26; $i++); is not right. Also an indexed C style for loop is relatively rare in Perl. for my $letter (a..z){} would be more common in this situation - but as mentioned before, even that is not necessary.
#!/usr/bin/perl -w use strict; my %dictionary = ('dog' => 'pet', 'horse' =>'animal', 'doggie' => 'also a pet', 'Bob' => 'person'); sortDictionary(); sub sortDictionary { foreach my $key (sort keys %dictionary) { # process only keys with lower case first letter # e.g. 'Bob' => 'person' would be skipped my $first_letter; next unless (($first_letter) = $key =~ /^([a-z])/); my $line = $key . '/' . $dictionary{$key}; print "processing line: $line\n"; writeFiles( $first_letter, $line); } } sub writeFiles { my ($first_letter, $line) = @_; my $filename = $first_letter . "_words.txt"; print "file: $filename adding $line\n"; open FILE, '>>', $filename or die "can not open $filename $!"; print FILE "$line\n"; close FILE; return; } __END__ processing line: dog/pet file: d_words.txt adding dog/pet processing line: doggie/also a pet file: d_words.txt adding doggie/also a pet processing line: horse/animal file: h_words.txt adding horse/animal
|
|---|