NAME
Class::RHash - objects based on a restricted hash
SYNOPSIS
package My::Class;
use base qw/Class::RHash/;
sub new {
my $c = shift;
return $c->attrs(
scalar => "hello world",
array => [ "hello", "world" ],
hash => { hello => "world" },
);
}
package main;
my $obj = My::Class->new;
print $obj->scalar;
print ( $obj->array )[1];
print $obj->hash("hello");
$obj->scalar("foobar");
$obj->array("foo", "bar"); # pushes onto the array
$obj->array(["foo", "bar"]); # sets the array
$obj->hash( foo => "bar" ); # changes a key
$obj->hash( {foo => "bar"} ); # sets all keys
DESCRIPTION
Creates objects based on a restricted hash, with intelligent AUTOLOADed accessor methods. You should use this as a base class.
METHODS
attrs
Sets and gets the allowed attributes of the object (keys of the hash).
- $obj->attrs
-
Returns a list of the attributes of the object.
- Class->attrs(foo => "bar")
-
Creates a new object with the given attributes. The type of each attribute (scalar, arrayref or hashref) will be fixed.
- $obj->attrs(foo => "bar")
-
Adds attributes to an existing object. This is to construct objects in subclasses, e.g.
sub new { my $c = shift; my $s = $c->SUPER::new(); return $s->attrs( new => "attrs", ); }. Croaks if any of the given attrs exist already, to help prevent classes treading on each other.
AUTOLOAD
Provides accessors for the elements of the hash. Attempts to call a method which does not have a corresponding key in the hash will pass the call to NEXT::ACTUAL::AUTOLOAD (see NEXT).
The behaviour of the method depends on whether the value of the attribute is a hashref, an arrayref or some other type of scalar. In the descriptions below, {} refers to a hashref argument, [] to an arrayref and "" to some other scalar.
- Hashref values
-
- $obj->hash( {} )
-
Sets all the keys in the hash to those given. Returns the new value, as a list in list context or a hashref in scalar context.
- $obj->hash( "" )
-
Returns the entry in the hash with the given key.
- $obj->hash( "", ... )
-
Sets or gets the entry in the hash with the given key. What happens depends on its type, in the same way as for attributes; so if the value is an arrayref, a scalar will be pushed or an arrayref will set the whole thing; if the value is a hashref then
$obj->hash( "key1", "key2" )will return$obj->{key1}{key2}; &c. - $obj->hash
-
Returns the whole hash, as a list in list context or a hashref in scalar context.
- Arrayref values
-
These always return the (new) array, as a list in list context or an arrayref in scalar context.
- Other scalar values
SEE ALSO
AUTHOR
Ben Morrow <Class-RHash@morrow.me.uk>
COPYRIGHT
Copyright (c) 2004 Ben Morrow
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.2 or, at your option, any later version of Perl 5 you may have available.