To do that I have used 3 resources/modules: Symbol, overload and tie(Hash).
Update:
See Object::MultiType - Perl Objects as Hash, Array & Scalar in the same time!
Source at: http://www.inf.ufsc.br/~gmpassos/Object-MultiType-0.01.tar.gz
Here's a code to show how to implement that (without tie):
To use the Hash reference with tie, in the new() just make:#!/usr/bin/perl my $obj = Multi->new() ; my $string = $obj ; $string .= '_x' ; print "*** $string\n" ; my $hash_a = $obj->{A} ; print "$hash_a\n" ; my $array_0 = $obj->[0] ; print "$array_0\n" ; $obj->method(qw(z y z)) ; print "Me as scalar: $obj\n" ; ######### # MULTI # ######### package Multi ; use Symbol ; use overload ( '""' => 'string' , '=' => 'copy' , '0+' => 'copy' , '@{}' => 'get_array' , '%{}' => 'get_hash' , 'fallback' => 1 , ) ; sub new { my $class = shift ; my $this = gensym ; bless($this,$class) ; my $scalar = 'Foo' ; *$this = \$scalar ; *$this = [qw(a b c)] ; *$this = {A => 10 , B => 20 , C => 30} ; return( $this ) ; } sub method { my $this = shift ; print "METHOD>> @_\n" ; } sub string { my $this = shift ; return( ${*$this} ) ; } sub copy { my $this = shift ; return( substr(${*$this} , 0 ) ) ; } sub get_array { my $this = shift ; return( \@{*$this} ) ; } sub get_hash { my $this = shift ; return( \%{*$this} ) ; } 1;
So now you can make:my %hash ; tie(%hash, 'TieHash' , $this) ; *$this = \%hash ; ## In the place of: ## *$this = {A => 10 , B => 20 , C => 30} ;
For me this works. I want to know if already exist some Perl module with that, or other way to do!$obj->{key} ; $obj->[0] ; print "Scalar: $obj" ;
If doesn't exit a module for that yet will make one... Maybe Object::MultiType. ;-p
Graciliano M. P.
"The creativity is the expression of the liberty".
In reply to Perl Object as Hash, Array & Scalar in the same time! ( $O->{k} | $O->[0] | $O ) by gmpassos
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |