Perl selectall_array - retrieve all data from array of array ref

3.4k views Asked by At

I am using DBI selectall_array to fetch all the data out of mysql. My query returns 1 columns for every row. But the selectall_array function returns an array of array ref for each row as listed below

$VAR1 = [
          '1.ptmp'
        ];
$VAR2 = [
          'e1.ptmp'
        ];
$VAR3 = [
          's2.ptmp'
        ];
$VAR4 = [
          'sw1.ptmp'
        ];
$VAR5 = [
          'w1.ptmp'
        ];

What I would like is a way to extract all the domains into a single array (no refs) or is there a DBI function which returns a full array of data without any references? I dont want to loop through all data or do fetchrow_array in a while loop. Looking for a single statement to do it all if possible?

Please see my code below:

my @mysqldata = $dbh->selectall_array('SELECT `domain` FROM dfs WHERE `id` IN ('.join(',',('?')x(scalar(@params))).')', {}, @params);
my @minus = array_minus( @all, @mysqldata );
2

There are 2 answers

0
beasy On BEST ANSWER

You can dereference the arrayrefs into one big array in one line like this:

my @all = map {@$_} $dbh->selectall_array($sql);

The map block applies @$_ to each row returned by selectall_array, which dereferences the arrayref.

3
David Collins On

Since you are only extracting one column you can try the selectcol_arrayref() method - de-referencing the array inline.

my @mysqldata = @{ $dbh->selectcol_arrayref('SELECT `domain` FROM dfs WHERE `id` IN ('.join(',',('?')x(scalar(@params))).')', {}, @params) };

UPDATE

As ysth suggested in the comments, you can use a postfix operator in newer versions of Perl (v5.20.0 and later) to dereference the value returned by selectcol_arrayref() - as in the following.

$dbh->selectcol_arrayref('SELECT domain FROM dfs', undef, @params)->@*;