#!/usr/bin/perl package Hash::AsObj; my %sub_class; sub new { my $class = shift; my $href = { @_ }; my $sub_class; # Keep hashes with the same set of keys in # the same package my $class_key = join "~", sort keys %$href; if ( exists $sub_class{$class_key} ) { $sub_class = $sub_class{$class_key}; } else { ( $sub_class = "$href" ) =~ tr/()/__/; $sub_class{$class_key} = $sub_class; } @{"${class}::Data::${sub_class}::ISA"} = "Hash::AsObj::Data"; bless $href, "${class}::Data::$sub_class"; } package Hash::AsObj::Data; use Carp (); sub DESTROY { 1 } sub AUTOLOAD : lvalue { my ( $class, $method ) = $AUTOLOAD =~ /^(.*)::(.+)$/ or Carp::croak "Invalid call to $AUTOLOAD"; Carp::croak "Can't locate object method $method via package $class" unless exists $_[0]->{$method}; *$AUTOLOAD = sub : lvalue { my $self = shift; if (@_) { $self->{$method} = shift; return $self; } $self->{$method}; }; goto &$AUTOLOAD; $Hash::AsObj::foo; } package main; use strict; use warnings; my $hobj = Hash::AsObj->new( a=>1, b=>2, c=>3 ,e=>5 ); print $hobj->a, "\n"; # It's an lvalue method! $hobj->a++; print $hobj->a, "\n"; # Or supply an argument to set values # I like method chaining - Your opinion may differ $hobj ->b(5) ->c(6); print "b: ", $hobj->b, " c:", $hobj->c, "\n"; # Error - this key doesn't exist print $hobj->d;

In reply to Hash::AsObj by runrig

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.