in reply to Printing different hash elements to different files

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

Replies are listed 'Best First'.
Re: Re: Printing different hash elements to different files
by tilly (Archbishop) on Apr 16, 2004 at 01:20 UTC
    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...