Erm, you are aware that using just <> does pretty much the same thing already?

Yes, that's right, but in this particular script I use my filehandles in a closure:

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

In reply to Re^2: input from STDIN or from a file by citromatik
in thread input from STDIN or from a file by citromatik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.