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

Hi all I'm very new to perl please bare with me. I'm trying to loop values from a database and print to a text file. The table contains many columns and I'm trying to dynamically print the values from each column without having to having hard code the column names. e.g $dat_ref2->{'num'}; for each column. I need to append each value from the column and print to a text file. any help is greatly appreciated :)
my $eachQuery = "SELECT * FROM example ORDER BY num; "; my $sth2 = $epm_db->Query($eachQuery); $sth2->execute(); # get example table headings my @eachCols = @{$sth2->{NAME}}; # or NAME_lc if needed my $EachVals = ""; while ( my $dat_ref2 = $sth2->fetchrow_hashref("NAME_lc") ) { foreach my $val(@eachCols) { #print $dat_ref2->{$_}; if ($EachVals eq "") { $EachVals = $dat_ref2->{$val}; } else{ $EachVals = $EachVals."\t".$dat_ref2->{$val}; } } print MYEach "$client\t$EachVals\r"; # printing values into csv output + file }

Replies are listed 'Best First'.
Re: looping hash
by TJPride (Pilgrim) on Mar 02, 2012 at 18:08 UTC
    Untested, but it should be a place to start:

    @keys = @{$sth2->{NAME}}; print join "\t", @keys; print "\r"; while ($record = $sth->fetchrow_hashref()) { print join "\t", map { $record->{$_} } @keys; print "\r"; }
      Thanks for the reply I Manage to figure it out below.
      my $Val=""; while ( my $dat_ref = $sth2->fetchrow_hashref("NAME_lc") ) { foreach my $val(@eachCols) { $Val = $dat_ref->{$val}; } }