Ok, a lot of times I just do what I feel is the quickest possible thing — the thing I can do without hardly thinking about it. I am Lazy, after all. ;-)
When I'm developing and debugging, I need to examine data structures, and for this, I usually reach for Data::Dumper. Sometimes my program will dump out many structures in one run.
By default, Data::Dumper encodes each dumped structure in an eval-able assignment statement, the receieving variable being named $VAR1. If I'm redirecting this output to a file, I could have a file containing numerous assignments to the same variable. The challenge: to load the file as perl code, in such a way that all the data structures are loaded and available. How can this be done if each statement overwrites the same variable?
Rather than munge the generated file, or figure out how to tweak Data::Dumper to do exactly what I need, I did something I knew would work without even having to think about it. I am, after all, Lazy.
I tied $VAR1 so that assignment to it actually pushes the value onto an array.
{ package Tie::Scalar::PushArray; sub TIESCALAR { my( $pkg, $ar ) = @_; bless { arrayref => $ar || [] }, $pkg } sub STORE { my $self = shift; push @{ $self->{'arrayref'} }, @_; } sub FETCH { my $self = shift; $self->{'arrayref'} } } tie our $VAR1, 'Tie::Scalar::PushArray'; do "data-dumper.out"; # load and eval. $_="VAR1=$VAR1\n"; # NB: It is necessary to do something like this # before trying to access $VAR1 as an arrayref! print "Loaded ".@$VAR1." elements\n";
|
|---|