The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

autobox::Bless - Guess which package a hash or hashref probably should be and blessed it

SYNOPSIS

  package purple;

  sub new { 
      my $package = shift;
      bless { one => 1, two => 2, }, $package;
  }

  sub three {
      my $self = shift;
      $self->{one} + $self->{two};
  }

  #

  package main;

  use autobox::Bless;

  my $purple = purple->new;   # optionally comment this out

  my %foo = ( one => 5, two => 17 );
  print %foo->three, "\n";    # 22!
  print %foo->four, "\n";     # not found, but %foo is now blessed into purple (yes, really)

DESCRIPTION

Attempts to guess which package an unblessed hash or hashref should be blessed into and bless it into that package on the fly.

Guessing is done by the fields (hash keys) present in the unblessed hash versus the fields in instances of various objects in memory. To be considered a match, the thing must find an object with all of the fields as the unblessed hash.

If that heuristic fails, as it would in the SYNOPSIS example where the <purple-new>> line is commented out, then a less nice strategy is attempted: all loaded packages are exampled for one containing the method called.

Why would anyone want this? You have a large legacy codebase that makes heavy use of hashes for collections of assortments of data and you want to shoehorn an OO-ish API onto it. Or perhaps you just want to play with an ultra lazy style of programming.

TODO

Mix in the my Foo::Bar $foo trick to give it (strong) hints
Do whatever Devel::LeakTrace does to figure out where stuff is allocated and assume that datastructures allocated in one package should be blessed into the same package
Do better approximate matching; don't require a single instance of an object to exist with all of the fields but instead permit an aggregate of all examples to contain the various different fields

BUGS

When used with autobox::Core or similar modules that add API methods to primitive values, method names might clash.

SEE ALSO

autobox, autobox::Core, perl5i, ...

http://twitter.com/scrottie/status/10706254646

AUTHOR

Scott Walters, <scott@slowass.net>

COPYRIGHT AND LICENSE

Copyright (C) 2010 by Scott Walters

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.12.0 or, at your option, any later version of Perl 5 you may have available.