georgecarlin has asked for the wisdom of the Perl Monks concerning the following question:
Good morning Monks
<EDIT> has been answered/fixed. the lc usage on a non-string causes the problem /<EDIT>
if an existing filehandle is passed to an object constructor via hashref, a subsequently invoked setter method triggers correctly but the stored value is a glob() rather than the filehandle, if it is passed as an argument to the same setter method it works just fine.
calling part
open(my $pfh, ">&", "STDOUT") or die("$0:ERROR Unable to redirect outp +ut to STDOUT. ERR: $?/$!\n"); my %conf = ( maxchilds => '20', waitforchilds => '180', mhandle => $pfh, ); print Dumper \%conf; my $fmo = fmanager->new(\%conf); print Dumper $fmo; $fmo->set_mhandle($pfh); print Dumper $fmo;
constructor and setter methods
sub new { my $class = shift; my $self = {}; my %childs; $self = { _handle => undef, _childs => \%childs, waitforchilds => '120', maxchilds => '10', mhandle => undef, }; bless($self,$class); if (@_){ my $hash_ref = shift; if ( ref($hash_ref) eq "HASH"){ while ( my ($k,$v) = ( each %{ $hash_ref } ) ) +{ $k = lc $k; $v = lc $v; if ( exists $self->{$k} && ! ($k =~ m/ +^\_/) ){ #is a valid config setting and is NOT a private met +hod my $method = "set_".$k; $self->$method($v); + #call appropriate setter method }else{ warn("$0:WARNING: skipping uns +upported configuration setting $k => $v in hash_ref $hash_ref\n"); } } }else{ die("$0:ERROR: argument passed to method 'new' + must be reference to a hash.\n"); } } return $self; } sub set_mhandle { my $self = shift; if (@_){ my $handle = shift; $self->{mhandle} = $handle; } return $self->{mhandle}; }
output
config hash
$VAR1 = { 'mhandle' => \*{'::$pfh'}, 'waitforchilds' => '180', 'maxchilds' => '20' };
fmo-object after constructor
$VAR1 = bless( { 'mhandle' => 'glob(0x2161670)', 'waitforchilds' => 180, '_handle' => undef, 'maxchilds' => 20, '_childs' => {} }, 'fmanager' );
fmo-object after manual setter call
$VAR1 = bless( { 'mhandle' => \*{'::$pfh'}, 'waitforchilds' => 180, '_handle' => undef, 'maxchilds' => 20, '_childs' => {} }, 'fmanager' );
Why the different behavior?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: passing filehandle to contstructor
by Anonymous Monk on Feb 28, 2014 at 09:17 UTC | |
by georgecarlin (Acolyte) on Feb 28, 2014 at 10:04 UTC |