Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re^2: File handles and loops

by dr.jekyllandme (Sexton)
on Jul 31, 2012 at 21:37 UTC ( #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.


Comment on Re^2: File handles and loops
Download Code
Re^3: File handles and loops
by tobyink (Abbot) 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
Node Status?
node history
Node Type: note [id://984666]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2014-10-25 00:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (138 votes), past polls