my $element; foreach $element(@Elements){ &process($element) or die; } sub process{ chdir("$path_to_the_data_directory")or die; my $outfile; #the $outfile name depends on $reg; open my $OUTFILE, q{>}, $outfile; my $infile = "data.txt"; open my $INFILE, q{<}, $infile; while (my $line = <$INFILE>){ # several operations which produce "$results" print $OUTFILE "$results\n"; } close $OUTFILE; chdir("$path_to_the_script_directory") or die; }