Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^2: File handles and loops

by dr.jekyllandme (Sexton)
on Jul 31, 2012 at 21:37 UTC ( [id://984666]=note: print w/replies, xml ) Need Help??


in reply to Re: File handles and loops
in thread File handles and loops

Hi tobyink, Thank you for replying. You, Neighbour, and the other Monks really helped me out. But I wanted to ask you how should I close the filehandle $fh after it has been opened? I've written my code somewhat similar to you and Neighbours but I am not sure if it is correct. Here is a snippet of the problem:
sub my_close { my( $fh ) = @_; + close($fh) or die "$!\n"; } + sub my_open { + my( $file, $mode ) = @_; + open my $fh, $mode, $file or die "$!\n"; + return $fh; } sub errors { + my( $file, $mode ) = @_; my $fh = my_open($file, $mode); my @errors = (); while( <$fh> ) { chomp; + next if /^[a-z]/; push( @errors, qq(Line $. '$_' does not begin with lowercase l +etter.) ); } my_close($fh); # Safe to close file like this??? + + return @errors; }
Thank you.

Replies are listed 'Best First'.
Re^3: File handles and loops
by tobyink (Canon) on Aug 01, 2012 at 06:29 UTC

    You rarely need to close lexical file handles. They automatically close once the variable goes out of scope. That is, if the my $fh is defined within a function, then once that function finishes executing, the file handle disappears.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://984666]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2024-03-28 19:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found