#1
  1. C Neophyte.
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Location
    Melbourne Australia
    Posts
    405
    Rep Power
    46

    Storing handles in hashrefs


    I'm trying to put together a class to act as a "reporting" class that I can use to sort my report files out

    1. Am I reinventing the wheel?

    2. How do I store a filehandle in a blessed hash in a way that works?

    from this quote: "If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead,"

    What am I doing wrong?


    perl Code:
     
    use strict;
    use warnings;
     
    package Reporter {
     
    	sub new {
    		my ($class, $fileName) = @_;				
    		my $self = {};				
    		bless $self, $class;		
    		$self->open($fileName) if(defined $fileName);		
    		return $self;
    	}
     
     
    	sub printReport {
    		my($self, $str) = @_;
    		if(defined $self->{fh} {			
    			print {$self->{fh}} $str;
    		}
    	}
     
    	sub open {
    		my($self, $fileName) = @_;		
     
    		open my $fh, "<", $fileName or die "could not open $fileName to write log";		
    		$self->{fh} = $fh;
    	}
     
    	sub close {
    		my($self) = @_;	
    		close $self->{fh};
    	}
     
    }
     
    1;
    For one to know everything, first one must accept he knows nothing.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,923
    Rep Power
    1225
    You have several syntax issues which are causing compilation errors.

    c:\testing>perl -c fuzzybunny.pl
    syntax error at fuzzybunny.pl line 20, near "}"
    syntax error at fuzzybunny.pl line 35, near "}"
    fuzzybunny.pl had compilation errors.
    In addition to those 2 errors, your syntax on the 'package' statement is wrong. That statement should terminate with a semicolon; it is not a block statement.

    Try this (untested) adjusted version.
    Code:
    package Reporter;
    
    use strict;
    use warnings;
    
    
    sub new {
        my ($class, $fileName) = @_;
        my $self = {};
        bless $self, $class;
        $self->open($fileName) if(defined $fileName);
        return $self;
    }
    
    sub printReport {
        my($self, $str) = @_;
        if(defined $self->{fh}) {
            print {$self->{fh}} $str;
        }
    }
    
    sub open {
        my($self, $fileName) = @_;
    
        open my $fh, "<", $fileName or die "could not open $fileName to write log $!";
        $self->{fh} = $fh;
    }
    
    sub close {
        my($self) = @_;
        close $self->{fh};
    }
    
    1;

IMN logo majestic logo threadwatch logo seochat tools logo