use IO::File; my %Registration_Number_Files; my $Registration_Number_Path = '/path/to/registration_numbers'; # ... sub write_record { my ($country_code, $header, $record) = @_ my $file_handle = $Registration_Number_Files{$country_code}; unless($file_handle) { my $file_name = "$Registration_Number_Path/$country_code.txt"; $file_handle = IO::File->new(">:raw:utf8", $file_name) or die "Failed to create '$file_name'"; print $file_handle $header; $Registration_Number_Files{$country_code} = $file_handle; } print $file_handle $record; }