in reply to Re^2: anonymous code blocks
in thread anonymous code blocks

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.