CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner: Re: [ChopperCharles] private and protected methods: Edit Log


Apr 3, 2012, 8:18 PM

Views: 6059
Re: [ChopperCharles] private and protected methods

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;
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;

use strict;
use warnings;
my $k = tester->new();
printf "s = %s\nt = %s\nu = %s\n", $k->s, $k->t, $k->u;

s = 1
t = 2
u = 3

(This post was edited by budman on Apr 3, 2012, 8:20 PM)

Edit Log:
Post edited by budman (User) on Apr 3, 2012, 8:20 PM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives