wouldbewarrior has asked for the wisdom of the Perl Monks concerning the following question:

I have a great big file that contains an unsorted, multilingual lexicon, that I am sorting, based on language. I've written code to do this a couple times, and am now looking for a more elegant solution to the problem. My question is, how can I (if there is, indeed, a way) print certain elements from the hash to different files, without explicitly specifying the file to which I want to print. My hash looks something like this

 $lexica{$language}{$word}{$counter}{$transcription}

What I would like to do is print everything correctly, according to language, with a single for loop, which, in my head, looks something like this:
foreach my $key (sort keys %lexica) { foreach $counter (keys(%{$lexica{$language}{$word}} )) { print $key "~$lexica{$language} \/$lexica{$language}{$word}{$cou +nter}\/ \n"; } } }

Replies are listed 'Best First'.
Re: Printing different hash elements to different files
by kvale (Monsignor) on Apr 15, 2004 at 22:30 UTC
    Computers cannot read minds, so you must at least open files with your desired names. Once you do that, however, printing can be automated:
    my %hash = ( one => "first bit", two => "second bit", ); # open files foreach my $file (keys %hash) { open $file, ">$file" or die "could not open $file: $!\n"; } # print elements foreach my $key (keys %hash) { print $key "$key => $hash{$key}\n"; }

    -Mark

      Not under strict.pm! You are actually accessing global package variables when you open on a string like that. If you want to make this work, you need to store the filehandles somewhere like this (5.6 on up) example:
      my %hash = ( one => "first bit", two => "second bit", ); my %fh; foreach my $file_name (keys %hash) { open (my $fh, ">", $file_name) or die "Could not write to '$file_name': $!"; $fh{$file_name} = $fh; } foreach my $key (keys %hash) { print {$fh{$key}} "$key => $hash{$key}\n"; }
      Of course if you've gone this far, then you may want a mapping between keys and file names...
Re: Printing different hash elements to different files
by tilly (Archbishop) on Apr 16, 2004 at 01:29 UTC
    Just open the file inside of the loop.

    A random tip. When looping over nested data structures, rather than dereferencing the nested data structure fully every time, save it into a lexical variable within the loop before you recurse. That way you will wind up writing something like print $fh "$language /$transcription/\n"; rather than something very long. Much easier to read. Avoiding redundant hash lookups is also faster, but of course that is less important.