
budman
User
Apr 3, 2012, 8:18 PM
Post #27 of 32
(5612 views)
|
Re: [ChopperCharles] private and protected methods
[In reply to]
|
Can't Post
|
|
You would need to store the values in an anonymous array
push @{ $self->{"_StructArray"} }, $element; push @{ $self->{"_StructArray"} }, @array; push @{ $self->{"_StructArray"} }, ( $e1, $e2, @array); # for array of hashes push @{ $self->{"_StructArray"} }, { a=>1, b=>2 }; # or just a hash $self->{"_StructArray"}{a} = 1; $self->{"_StructArray"}{b} = 2; To access them:
use Data::Dumper; print Dumper( $self->{"_StructArray"} ); print $self->{"_StructArray"}[0]; foreach my $i ( @{ $self->{"_StructArray"} } ) { print "$i\n"; } # for array of hashes foreach my $i ( @{ $self->{"_StructArray"} } ) { foreach my $k (sort keys %{$i}) { print "$k $i->{$k}\n"; } } Note: When key names start with an underscore, you should quote the key name as it may lead to issues with strict pragma. I took a look at Class::Struct. My quick guess is that it takes each key you add in the struct method and auto-generates a setter and getter.
$element_value = $obj->s; # element value $obj->s('new value'); In order for your object to work like this, you would need to create the setter and getters for each key. This can be done by the AUTOLOAD to create the getter/setter on the fly. Otherwise, it's pretty monotonous. For what it's worth, to save time, headaches, and use proven well tested code - use Moose.
sub s { my ($self) = shift; if (@_) { $self->{'_Struct'}{s} = shift } return $self->{'_Struct'}{s}; } sub t { my ($self) = shift; if (@_) { $self->{'_Struct'}{t} = shift } return $self->{'_Struct'}{t}; } These can be pretty repetitive and you notice a pattern. This is the idea behind Class::Struct, you can use AUTOLOAD, or better maybe to build it at compile time using BEGIN. The attributes should be unique, or you can override existing subs.
# handle undefined subs package tester; BEGIN { my @attribs = qw(s t u); for my $attrib ( @attribs ) { no strict 'refs'; # add getter/setter method *{"$attrib"} = sub { my $self = shift; if (@_) { $self->{'_Struct'}{$attrib} = shift }; return $self->{'_Struct'}{$attrib}; }; } } sub new { my $class = shift; my $self = {}; $self->{'_Struct'} = {}; bless ($self, $class); return $self; } 1; #!/usr/bin/perl use strict; use warnings; my $k = tester->new(); $k->s(1); $k->t(2); $k->u(3); printf "s = %s\nt = %s\nu = %s\n", $k->s, $k->t, $k->u; Output: s = 1 t = 2 u = 3
(This post was edited by budman on Apr 3, 2012, 8:20 PM)
|