Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: a simple matter of elegance

by lima1 (Curate)
on Oct 03, 2007 at 10:27 UTC ( #642366=note: print w/replies, xml ) Need Help??


in reply to a simple matter of elegance

You can do that with AUTOLOAD, for example with:
package MyAutoloadDemo; use strict; use warnings; use Carp; our $AUTOLOAD; sub new { my $class = shift; my $self = {}; $self->{'data'}->{'name'} = 'spiros'; $self->{'data'}->{'address'} = 'london'; bless $self, $class; return $self; } sub AUTOLOAD { my $self = shift; my $type = ref $self; my $name = $AUTOLOAD; $name =~ s/.*://; # strip fully-qualified portion if (!exists $self->{data}->{$name} ) { croak "Can't access $name field in class $type"; } return $self->{data}->{$name}; } 1;
use MyAutoloadDemo; my $demo = MyAutoloadDemo->new(); warn $demo->name; warn $demo->address; warn $demo->unknown;
This prints:
spiros at test.pl line 4. london at test.pl line 5. Can't access unknown field in class MyAutoloadDemo at test.pl line 6
But you probably want something from CPAN's Class:: namespace, eg. Class::MethodMaker, Class::Accessor, Class::Std, ..

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://642366]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2021-04-14 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?