in reply to Perl's equivalent to Python's hasattr and getattr? (class variable details)

Hello,

I think you may want something like Class::Accessor. Class::Accessor is just one of many modules that may work for you. You may want to look at the Class:: namespace in the cpan.

  • Comment on Re: Perl's equivalent to Python's hasattr and getattr? (class variable details)

Replies are listed 'Best First'.
Re^2: Perl's equivalent to Python's hasattr and getattr? (class variable details)
by MistaMuShu (Beadle) on Jul 28, 2005 at 23:46 UTC
    Wow, that hits it right on the spot! I find it weird that this isn't builtin. Maybe I'll skim through and look up how Class::Accessor is implemented. Is it possible to do something similar theorically by manipulating symbol tables?

      Class::Accessor is built using the symbol table. Here is the _mk_accessors as an example.

      { no strict 'refs'; sub _mk_accessors { my($self, $maker, @fields) = @_; my $class = ref $self || $self; # So we don't have to do lots of lookups inside the loop. $maker = $self->can($maker) unless ref $maker; foreach my $field (@fields) { if( $field eq 'DESTROY' ) { require Carp; &Carp::carp("Having a data accessor named DESTROY in +". "'$class' is unwise."); } my $accessor = $self->$maker($field); my $alias = "_${field}_accessor"; *{$class."\:\:$field"} = $accessor unless defined &{$class."\:\:$field"}; *{$class."\:\:$alias"} = $accessor unless defined &{$class."\:\:$alias"}; } } }