http://www.perlmonks.org?node_id=853655


in reply to File Reading and Closing confusion

and that the second case might warrant undefing the variable $/ and then maybe splitting or doing array manipulation.

Erm...no. You undefine $/ to slurp a file into a scalar; whereas @array = <FH> populates @array with lines, trailing $/ chopped off implicitly or not, according to the command line switch -l (update: wrong, implicit chomp only happens in combination of l with the n or p switch).

What I am confused about is when in a loop I have something like while(<FH>){...}, is this any different than $line=<FH> or are these granularly the same?

Run perldoc -f readline. That said, no, those are not the same: while(<FH>){...} assigns to $_, but $line=<FH> assigns to $line. Other than that, they are the same.

To delete a file we use unlink and to close a file handle we use close and then we have undef which can also close a filehandle for us, my heart tells me that using undef this way is somewhat frowned upon or sinful, is that justified?

That's not frowned upon or sinful, since a common idiom is

my @lines = do { open my $fh, '<', $file or die "$file: $!\n"; <$fh> } +;

Perl scoping rules apply. As can be seen reading open, file handles are closed if they get out of scope (and are thus undefined implicitly). So, nothing wrong about undef $fh.

One caveat, though: You might encounter problems closing a file handle - for example flushing buffers and closing a file residing on a remote mountpoint, which became unavailable during operation of your program.

So, it is always wise to close your file handles explicitly and check the return value.