in reply to Re: modules, exporting, and indirect filehandles
in thread modules, exporting, and indirect filehandles

thanks. i came up with this based off the chatterbox:

module:
sub open_file { my ($mode, $file) = @_; my $fh = gensym(); open $fh, "$mode$file" or croak("could not open '$file': $!"); return \*$fh; }
file:
my $LOG = open_file('<','log.txt'); while(<$LOG>) { print; }
why will this not work?

open $fh, $mode, $file or croak("could not open '$file': $!");

which gives:

Too many arguments for open at MyPackage.pm line 55, near "$file or" BEGIN failed--compilation aborted at ./moduletest.pl line 4.

Replies are listed 'Best First'.
Re^3: modules, exporting, and indirect filehandles
by ikegami (Patriarch) on Aug 09, 2005 at 20:23 UTC

    It looks fine, and it works for me when I run that. Are you sure you're using the files you think you are using.

    By the way, \* in return \*$fh; is useless. return $fh; will return the same thing.

    Starting with Perl 5.6, open accepts the mode and file name as seperate arguments. It's safer to use the three argument form and concatenating the mode and file name:

    sub open_file { my ($mode, $file) = @_; my $fh = gensym(); open $fh, $mode, $file or croak("could not open '$file': $!"); return $fh; }

      With 5.6, there's no need to use gensym() either:

      sub open_file { my ($mode, $file) = @_; open my $fh, $mode, $file or croak("Could not open '$file': $! +"); return $fh; }
        I know. You just duplicated my first reply (except mine also supports the two-arg open). The OP stated he didn't want to use that.
      i thought i had replied, but apparently i forgot to follow it all the way through. thank you for your help; this is working well :)
Re^3: modules, exporting, and indirect filehandles
by eff_i_g (Curate) on Aug 09, 2005 at 20:19 UTC
    ahhh... it's my version of perl.