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
}
Yes, I know that this sounds paranoic, but I find some benefits using this (private filehandles, a bit of encapsulation, access to $ifh a bit faster, etc...
Given this scenario I don't know if using <> is easy or even possible.
Not to mention that while( <$ifh> ) { ... } isn't going to return false until there's an EOF condition on STDIN in which case you're not really going to gain much by not closing it (at least nothing useful that I can think of off hand).
Sure, I agree, but you can have something like this:
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 = <STDIN>;
If you happen to close STDIN, that last statement would give you an error.
Ok, I will stop here, or you will think that I'm really a paranoic :-)
citromatik |