sub foo {
my $self = shift;
my $filename = shift;
open FH, $filename or die "Can not open file: $!\n";
$self->{'fh'} = \*FH;
}
####
package FOO;
use diagnostics;
sub new {
my $class = shift;
my $self = { blahh => 'blah', };
my (%opts) = @_;
return unless (exists $opts{'input'} && exists $opts{'output'});
%$self = ( %$self, %opts );
bless $self, $class;
$self->{'inp_fh'} = $self->_open_read;
$self->{'out_fh'} = $self->_open_write;
return $self;
}
sub read_line {
my $self = shift;
my $fh = $self->{'inp_fh'};
return <$fh>;
}
sub write_line {
my $self = shift;
my $data = shift;
my $fh = $self->{'out_fh'};
print $fh $data;
}
sub _open_read {
my $self = shift;
{
local *FH;
open FH, $self->{'input'} or die "Couldn't open: $!\n";
return \*FH;
}
}
sub _open_write {
my $self = shift;
{
local *FH;
open FH, ">$self->{'output'}" or die "Couldn't open file: $!\n";
return \*FH;
}
}
sub DESTROY {
my $self = shift;
close ($self->{'inp_fh'});
close ($self->{'out_fh'});
}
package main;
use strict;
my $data;
my $foo = FOO->new('input'=>"inp.dat", 'output'=>"out.dat") ||
die ("Error creating new FOO!!\n");
for my $key (keys %$foo) {
print "KEY: $key \tVAL: $foo->{$key}\n";
}
while ($data = $foo->read_line) {
$foo->write_line($data);
}
##
##
KEY: out_fh VAL: GLOB(0x1a75098)
KEY: inp_fh VAL: GLOB(0x1a75038)
KEY: input VAL: inp.dat
KEY: blahh VAL: blah
KEY: output VAL: out.dat
##
##
KEY: out_fh VAL: *FOO::FH
KEY: inp_fh VAL: *FOO::FH
##
##
sub _open_write {
my $self = shift;
my $fh = do { local *FH };
open $fh, ">$self->{'output'}" or die "Couldn't open file: $!\n";
return $fh;
}