in reply to Class / package weak association

Hm ... my first idea was to serialize the blessing package, than I realized that in most cases packages are already serialized - in a text representation - in the representing module.pm ...

Of course you could complain that subs could have been added dynamically outside the module.

So one could think about dumping the STASH ...

DB<26> sub BLA::foo { print "BLA::foo"} DB<27> use Data::Dumper DB<28> p Dumper \%BLA:: $VAR1 = { 'foo' => *BLA::foo, 'AUTOLOAD' => *BLA::AUTOLOAD };

... alas, Data::Dumper won't serialize the sub's body.

Other serializers allow B::Deparse to hook in ( Data::Dump probably, IIRC? ) , but this source representation is not 100% reliable.

And that's where - in my humble opinion - your interesting idea hits a wall.

As long as one can't reliably serialize the code of the subs of a class, one will need to resort to add the class' code manually.°

While it's possible to introspect in which file and line a sub was defined, this will only help if it was static source and not a dynamically built eval $SOURCE .

In short: Serializing the methods of a class is very hard in Perl if it has to be fail proof.

(I was too eager to meditate and too lazy to search, you may want check if CPAN already offers a solution for that :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery

°) On a side note: JS has a method .toSource() for such introspection, which unfortunately lacks in Perl.

update

Anyway ... I'd be interested to know the use case you see. Packages are after all _global_, so resurrecting them might lead to so heavy side effects, that manual interference is needed anyway.

Replies are listed 'Best First'.
Re^2: Class / package weak association
by Corion (Patriarch) on Jun 08, 2021 at 06:45 UTC

    To expand a bit, the configuration setting is $Data::Dumper::Deparse to make Data::Dumper also dump the (deparsed) source code of code references. But as LanX already said, the source representation is functionally mostly identical but will not necessarily represent the original code identically.

    The interesting part is once you have subroutines closing over common variables, like for example getters/setters:

    my $name = 'foo'; my $package = { getter => sub ( $self ) { return $self->{$name} }, setter => sub ( $self, $value ) { return $self->{$name} = $value } +, }

    You need to dump these at once so that Data::Dumper dumps the reference to the common variable $name as a single variable. This happens whenever your class has autogenerated methods (like with Moo, Moose etc.).

    Depending on how much control you have over the source code of the class to be dumped, this can make things far more hairy than you want.