Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Dumping Tie Objects

by bichonfrise74 (Vicar)
on Nov 20, 2009 at 21:25 UTC ( #808531=perlquestion: print w/replies, xml ) Need Help??
bichonfrise74 has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have been playing around with the 'tie' operator and basically I want be able to 'dump' the object using Data::Dumper.

In the code specifically in the line,
print Dumper \%test;
Nothing is dump at all. I am not sure why. I read somewhere that I should treat variables binded by the tie operator as normal variables. So, normally the above syntax should show me the content of the hash. Any thoughts?

Below is the code.
#!/usr/bin/perl use strict; use Data::Dumper; tie( my %test, 'Sample_Tie_Class' ); $test{'hello'} = 'hi'; print "$test{'hello'}\n"; print Dumper \%test; package Sample_Tie_Class; use strict; sub TIEHASH { my $class = shift; bless { 'value' => {}, }, $class; } sub STORE { my ($self, $key, $value) = @_; $self->{'value'}->{$key} = $value; } sub FETCH { my ($self, $key) = @_; return $self->{'value'}->{$key}; } sub FIRSTKEY { }

Replies are listed 'Best First'.
Re: Dumping Tie Objects
by bichonfrise74 (Vicar) on Nov 20, 2009 at 21:42 UTC
    Nevermind. The reason why the Dumper line didn't work because I have not defined the FIRSTKEY and NEXTKEY functions.
    sub FIRSTKEY { my ($self) = @_; each %{ $self->{'value'} }; } sub NEXTKEY { my ($self) = @_; each %{ $self->{'value'} }; }
    Once I added the two functions, then the Dumper worked. But interestingly, how come Perl didn't tell me that the two functions need to be defined at all?
      I think (perhaps more knowledgeable monks can confirm) that the  FIRSTKEY function needs to be defined such that it always returns the first key of the hash. As it is, it's the same as  NEXTKEY and only returns the first key upon the first iteration or when iteration wraps around to the beginning again.

      Try (untested):

      sub FIRSTKEY { my ($self) = @_; scalar keys %$Self; return each %{ $self->{'value'} }; }
      Update: keys resets the internal iterator of a hash. In void context, this happens with no other overhead, so the use of scalar above is only for the purpose of self-documentation.

      Also: On second thought, I would be inclined to implement  FIRSTKEY in terms of  NEXTKEY (also untested):

      sub FIRSTKEY { my ($self) = @_; keys %$Self; return $self->NEXTKEY; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://808531]
Approved by johngg
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2018-05-22 15:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?