tags:

views:

15

answers:

1

I have to simulate an array as if it was returned from Net::DBI fetchall_arrayref function.

Lets say that the SQL query is something like "SELECT data1,data2,data3 from table1 "

I have an XML file as

<type1> 
  <data1>a</data1>
  <data2>b</data2>
  <data3>c</data3>
</type1>
<type1> 
  <data1>da</data1>
  <data2>db</data2>
  <data3>dc</data3>
</type1>

I read this XML file using XML::Simple to get a complete data array like:

$VAR1 = {
          'type1' => [
                     {
                       'data2' => 'b',
                       'data3' => 'c',
                       'data1' => 'a'
                     },
                     {
                       'data2' => 'db',
                       'data3' => 'dc',
                       'data1' => 'da'
                     }
                   ]
        };

How do I get this array to a form which will be same as the one returned by fetchall_array_ref?

I am doing something like this:

#REad from testin.xml file
$data = $xml->XMLin('testin.xml');

@testdata = $data->{type1};

$i = 0;
foreach $e (@{$data->{type1}})
{
        $simulate_data[$i++] = \$e;
}

Please help.

+1  A: 

fetchall_arrayref() returns a reference to an array that contains one reference per row. You want to turn each set of values in the hash reference into an array reference. This should work:

my $arr_ref;
foreach my $hashref ( @{$data->{'type1'}} ) {
  push @$arr_ref, [ sort values %$hashref ];
}

This gives me the following (via Data::Dumper):

$VAR1 = [
          [
            'a',
            'b',
            'c'
          ],
          [
            'da',
            'db',
            'dc'
          ]
        ];

(Aside: Please always put use strict; in your programs.)

CanSpice