sub get_closure { my ($filename) = @_; open my $ifh, "<", $filename or die $!; return sub { # subroutine that returns one record per call } } # and then: my $getNextRecord = get_closure($filename); while ( my $record = $getNextRecord->() ){ # do something with $record } #### my $file = shift @ARGV; my $ifh; my $is_stdin = 0; if (defined $file){ open $ifh, "<", $file or die $!; } else { $ifh = *STDIN; $is_stdin++; } while (<$ifh>){ # Process } #close $ifh unless $is_stdin; close $ifh; ## code passes... ## ... and my $another_value = ;