after reading open, I realize that when in a sub the first is example is good because you dont have to worry about closing the filehandle - it simply goes out of scope. Does the same hold true when in MAIN? Do I not have to cose the fh? Or am I missing something?
I second that, but it's not limited to subs which introduce nothing but a "lexical scope", so the keyword here is the latter. For example you may have
for (@files) { # open my $fh, '<', $_ or (warn "$_: $!\n"), next; push @first_lines, scalar <$fh>; }

Or, consider the following example script that exploits open as a cheap way to parallelize a series of possibly slow operations:

#!/usr/bin/perl use strict; use warnings; die "Usage: $0 <net>\n" unless @ARGV == 1; # Rudimentary check on the argument (my $net=shift) =~ s/\.0+$/./ or die "Supply an IP of the form <#.#.#.0>\n"; print 'Begun pings at ' . localtime, "\n"; my @p; open $p[@p], '-|', "ping -w 5 -c 5 $net$_" or die "Couldn't start ping for $net$_: $!\n" for 1..255; undef $/; print map <$_>, @p; __END__
Note:

In any case, to answer your question: yes! "lexical filhandles" are closed automatically on scope exit. But there are situations in which you may need to explicitly close them. If I don't need to, I don't; others' opinion may vary: see e.g. philcrow's reply.

Also, a filehandle can hold more than regular files, and there's stuff you still have to explicitly close.


In reply to Re^3: anonymous code blocks by blazar
in thread anonymous code blocks by tcf03

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.