... my $temp; # declare $temp before the loop while (...) { ... } close FASTQIN; my %count_seq; open my $fh, ... # $temp is still in scope ... #### $temp = $head . $seq; print $temp; #### close FASTQIN; my %count_seq; if (defined $temp) { open my $fh, '<:encoding(UTF-8)', $temp or die "Cannot open $temp $!"; while (<$fh>) { ... } }