[ABE.pm] Re: array references?

Phil Lawrence phil at five-lawrences.com
Fri Oct 1 23:20:42 CDT 2004


On Oct 1, 2004, at 18:05, Faber Fedor wrote:

> On 01/10/04 15:51 -0400, Phil Lawrence wrote:
>>
>> On Oct 1, 2004, at 15:35, Faber Fedor wrote:
>>
>>> How does one access elements in an array reference?  I'v done this:
>>>
>>> my $data_array = $dbh->selectall_arrayref("select A, B from
>>>        $table where realdate =  '" . $fulldate ."'");
>>>
>>> and I get something back, I just can't figure out how to access the
>>> data
>>> in column A or B.  How would I print out each pair of values?
>>
>> print $aref->[0][0];  #prints first elem of first row
>
> I hacked this together from something I read on usenet:
>
>     my $data_array = $dbh->selectall_arrayref("select id, weight from
> 	    $table where realdate =  '" . $fulldate ."'");

my $nested_arefs = $dbh->selectall_arrayref(<<"ENDSQL", undef, 
$fulldate);
     SELECT id
          , weight
       FROM $table
      WHERE realdate = ?
ENDSQL


>
>     my $sum ;
>     # forsome reason =+ didn't work here :-?
>     foreach my $i  (@{$data_array}) {
> 	$sum = $sum + @$i->[1];
>     }

# it's +=, not =+  :-)

my $sum;
for my $record_aref (@$nested_arefs)
{
     $sum += $record_aref->[1];
}

-- OR --
my $sum;
$sum += $_->[1] for @$nested_arefs;


>
>     foreach my $i  (@{$data_array}) {
> 	@$i->[1] = 100*(@$i->[1]/$sum);
>     }

$_->[1] = 100 * ($_->[1]/$sum) for @$nested_arefs;


>     open(OUTFILE, "> $outfile");
>
>     foreach my $i  (@{$data_array}) {
> 	printf OUTFILE "%8s, %5.4f \n", @$i->[0], @$i->[1] ;
>     }
>
>     close(OUTFILE);

open OUTFILE, ">$outfile" or die;
printf OUTFILE "%8s, %5.4f \n", @$_[0,1] for @$nested_arefs;
close OUTFILE;


> but there's got to be a more elegant way.

How do those examples look to you?  better?

Be careful, i see you were using the '@' sigil when all you needed was 
the '$' sigil.
Example:
   @$i->[1]
should be:
   $i->[1]

I think that's because the infix operator ('->') combined with the 
'square' brackets already implies the fact that you're dereferencing an 
aref.

You'll probably pick it up the sigil thing pretty quick.


>> Also, fire up the perl debugger and make like so:
>
> I really have to learn how to use that thing...

I don't know how to *really* use it, but I can do a few things:

~ phil$ perl -de0

Loading DB routines from perl5db.pl version 1.22
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   0
   DB<1> $aref = [ [1,2], [3,4] ]

   DB<2> x $aref
0  ARRAY(0x892b50)
    0  ARRAY(0x801318)
       0  1
       1  2
    1  ARRAY(0x892b20)
       0  3
       1  4
   DB<3>  q
~ phil$


Oh, and don't forget these at the top of *every* script:
use warnings;
use strict;
use diagnostics;


:-) prl



More information about the ABE-pm mailing list