Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

DBIx::Class Looping thru resultset

by phildeman (Scribe)
on Apr 29, 2016 at 20:04 UTC ( [id://1161907]=perlquestion: print w/replies, xml ) Need Help??

phildeman has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

Can variables be used in place of column names when looping through DBIx::Class array of objects.
For example:

my @db_colnames = ('lastname','firstname','middlename'); my @rows = $schema->resultset( 'myTable' )->search({}, {order_by => [qw +/ lastname firstname middlename /] } ); foreach my $row (@rows) { foreach my $col (@db_colnames) { print $row->$col ."\t"; } print "\n"; }

No value printed. However, when I used the actual column name to retrieve the data, it worked fine. For example:

. . print $row->lastname . "\t" . $row->firstname . "\t" . $row->middlenam +e . "\t"; print "\n"; . .

Thanks for your help.

Replies are listed 'Best First'.
Re: DBIx::Class Looping thru resultset
by Your Mother (Archbishop) on Apr 29, 2016 at 20:29 UTC

    That definitely works; method name as $scalar. Not sure where it's falling down for you. As someone allergic to any kind of string concatenation, implied or literal, might I suggest something more like this–

    my @db_colnames = qw( lastname firstname middlename ); my $rs = $schema ->resultset('myTable') ->search({}, { order_by => \@db_colnames }); for my $row ( $rs->all ) { my %data = $row->get_columns; print join("\t", @data{@db_colnames}), "\n"; }
Re: DBIx::Class Looping thru resultset
by Myrddin Wyllt (Hermit) on Apr 30, 2016 at 13:34 UTC

    If you just want the data in the column, rather than any inflated object DBIC has associated with it (DateTime, foreign key Row objects etc.), it's probably best to use $row->get_column($col), which avoids the variable / method name substitution.

    Having said that, I've just tried your code with one of my own databases and it works fine. If there was a problem with the column names, I would expect DBIx to complain, so it's possibly a typo somewhere else.

Re: DBIx::Class Looping thru resultset
by Ovid (Cardinal) on May 02, 2016 at 06:00 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1161907]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-26 06:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found