Looping through Class::Accessor accessors

D

Derek Basch

Hi Everyone,

I began using Class::DBI and love it. However, there are situations
where I want to loop through the Class::Accessor accessors for an
object and also get the name of the accessor as I loop through.

For instance here is some psuedo-perl that I wrote to visualize what I
need:

# returns an array of objects
my @gpsaccounts = Database::Members::Gpsaccounts->search($user_id);

# loop through the array of objects
foreach my @row_class (@gpsaccounts) {
# loop through the objects accessors
foreach $class_accessor (@row_class) {
# print the accessors name and value
print "$class_accessor_name: $class_accessor_value\n"
}
}

Yes, I know that the above is syntactically unpossible but I don't know
how else to express it.

Here's how you would normally do it:

my @gpsaccounts =
Database::Members::Gpsaccounts->search_gpsaccounts($user_id);

foreach(@gpsaccounts) {
print $_->fullname . "\n";
print $_->user . "\n";
print $_->email . "\n";
print "------------------------" . "\n";
}

Any ideas? I am a newer Perl programmer so any help is appreciated.

Thanks,
Derek Basch
 
D

Derek Basch

Thanks for all the help Steven.

However, the solution suddenly occured to me last night. I was
declaring my accessors with the 'columns' function of the Class::DBI
module. Therefore, there must be a hash or something somewhere to loop
over. I found that Class::DBI objects have various column retrieval
functions. I used the 'all_columns' function that returns the column
names. Works great :).


sub test {
my @gpsaccounts = Members::Gpsaccounts->search($user_id);
foreach my $row (@gpsaccounts) {
foreach my $column ($row->all_columns()) {
print $column . "\n";
}
}

Derek Basch
 
D

Derek Basch

However, the solution suddenly occured to me last night. I was
declaring my accessors with the 'columns' function of the Class::DBI
module. Therefore, there must be a hash or something somewhere to loop
over. I found that Class::DBI objects have various column retrieval
functions. I used the 'all_columns' function that returns the column
names. Works great :).


sub test {
my @gpsaccounts = Members::Gpsaccounts->search($user_id);
foreach my $row (@gpsaccounts) {
foreach my $column ($row->all_columns()) {
print $column . "\n";
}
}

Derek Basch


Here's an improved version:

sub test {
my @gpsaccounts = Members::Gpsaccounts->search($user_id);
foreach my $row (@gpsaccounts) {
foreach my $column ($row->columns()) {
print $row->$column . "\n";
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top