Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more concise way to write this in Perl?

Tags:

file

perl

This subroutine is passed an array of file handles to close, which it closes one by one using the foreach loop:

sub closef
{
    foreach(@_) {
        my $fh = shift;
        close $fh;
    }   
}

Where all can this simple subroutine be modified to make it better?

Should I use close shift instead of doing it in two lines?

like image 212
Lazer Avatar asked Nov 28 '22 01:11

Lazer


1 Answers

The most concise way is to use lexical filehandles which automatically close when they go out of scope:

sub firstline {
    open( my $in, shift ) && return scalar <$in>;
    # no close() required
}

See perldoc perlopentut.

like image 116
Eugene Yarmash Avatar answered Dec 06 '22 09:12

Eugene Yarmash