sub work_with_file { my ( $filename, $fh, $hash) = @_; ..... ..... $hash->{$dt} = $lines if $errorFound; } work_with_file($_, $fh, \%hash); foreach my $key (sort keys %hash) { print $fh "$key:\n$hash{$key}\n"; }