Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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.

Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://984666]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2018-06-25 12:55 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.