Hello all,

Recently I faced one scenario with references and array slice in perl.

I used following program to retrieve the rows from a table in Oracle using
Perl DBI.

As shown in the program, I did following steps to retrieve the rows :-


   - used "fetchall_arrayref" to get the array reference to the complete
   table
   - dereferenced the reference "fetchall_arrayref" and iterate one by one
   over each row "$row" in a foreach loop
   - further deferenced "$row" to get the columns one by one

Now here is the problem,

I used "${$row}[0]", "${$row}[1]" etc one by one to get all the columns for
a particular code. On one of the production code which I am working, they
have used "@{$row}[0]" , "@{$row}[0]" instead of earlier. The results for
both of them were same.

When I did a through debugging on this, I found that "@{$row}[0]" or
"@{$row}[1]" etc is taken as array slice by perl with only one member so it
returns the value of the column in scalar and not in list context. With
"${$row}[0]" or "${$row}[1]" etc, the column value is returned in scaler
context.

I want to know whether it's appropriate to use "@{$row}[0]" , "@{$row}[1]"
instead of "${$row}[0]", "${$row}[1]" though both of them gives same result
?

# cat o1.pl
#!/usr/bin/perl
##!/u01/app/oracle/product/10.1.0/db_1/perl/bin/perl
# Example PERL DBI/DBD Oracle Example on Oracle 10g
use strict;
use warnings;
use DBI;
my $dbname = "*****";   ## DB Name from tnsnames.ora
my $user = "*****";
my $passwd = "*****";
#### Connect to the database and return a database handle
my $dbh = DBI->connect("dbi:Oracle:${dbname}", $user, $passwd);
if($dbh){
        print("Connected as user $user\n");
} else {
        print("Failed to connect!\n");
        exit;
}
#### Prepare and Execute a SQL Statement Handle
my $sth = $dbh->prepare("SELECT owner,table_name,num_rows FROM all_tables");
# my $sth = $dbh->prepare("SELECT * FROM all_tables");
$sth->execute();
my $allTablesRow = $sth->fetchall_arrayref();
foreach my $row (@{$allTablesRow})
{
        if (defined ${$row}[0])
        {
                print "<${$row}[0]>";
        }
        else
        {
                print "<NULL>";
        }
        if (defined ${$row}[1])
        {
                print "<${$row}[1]>";
        }
        else
        {
                print "<NULL>";
        }
        if (defined ${$row}[2])
        {
                print "<${$row}[2]>";
        }
        else
        {
                print "<NULL>";
        }
        print "\n";
}
#### Disconnect
#$dbh->disconnect;
You have mail in /var/spool/mail/root
#


Thanks & Regards,
Amit Saxena

Reply via email to