[ABE.pm] Re: array references?
Ricardo SIGNES
rjbs-perl-abe at lists.manxome.org
Sat Oct 2 15:17:47 CDT 2004
* Faber Fedor <faber at linuxnj.com> [2004-10-01T18:05:11]
> I hacked this together from something I read on usenet:
>
> my $data_array = $dbh->selectall_arrayref("select id, weight from
> $table where realdate = '" . $fulldate ."'");
I'm not sure about the use of $table, but at least consider
$dbh->selectall_arrayref(
"SELECT id, weight FROM table WHERE realdate = ?",
undef,
$fulldate
);
This will use proper quoting to get the date in, and avoid SQL injection
attacks.
> my $sum ;
> # forsome reason =+ didn't work here :-?
Because it's +=
> foreach my $i (@{$data_array}) {
> $sum = $sum + @$i->[1];
> }
$sum += @{$_->[1]} for @$data_array;
> foreach my $i (@{$data_array}) {
> @$i->[1] = 100*(@$i->[1]/$sum);
> }
> open(OUTFILE, "> $outfile");
Eliminate the foreach.
open my $output, '>', $outfile;
This creates a lexical filehandle-reference, which will autoclose when
it goes out of scope. There are other benefits. Check "perldoc
perlopentut"
> foreach my $i (@{$data_array}) {
> printf OUTFILE "%8s, %5.4f \n", @$i->[0], @$i->[1] ;
> }
foreach (@$data_array) {
printf $output "%8s, %5.4f \n",
$_->[0],
(100*($_->[1]/$sum));
}
This combines the previous loop into this one. You could reassign the
element in the arrayref, if you wanted, but I was guessing you just did
that to get at it here. You could also do something like this:
print $output
map { sprintf "%8s, %5.4f\n", $_->[0], (100...) }
@$data_array;
but that's just a question of whether you like reading English or
Hebrew.
> close(OUTFILE);
close $output;
I think that's less inelegant. Surely there are other, possibly better,
ways to do this.
--
rjbs
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/archives/abe-pm/attachments/20041002/111ad26f/attachment.bin
More information about the ABE-pm
mailing list