in reply to Weird DBI/Array Use

If I know that my query is going to return only one entry, how do I avoid using a loop to gather the returned data? Anything I try just returns me an array reference.
my $result = db_execute($SQL); foreach(@$result){ my ($title,$body) = @$_; print $title; }
Thanks,
madhatter

Replies are listed 'Best First'.
Re: Re: Weird DBI/Array Use
by Fastolfe (Vicar) on Jan 08, 2001 at 03:48 UTC
    If you have an array reference that you "know" will only contain one item, then it sounds like you just want to access the first element of the array:
    my $result = db_execute($SQL)->[0]; my ($title, $body) = @{$result}; # or my ($title, $body) = @{db_execute($SQL)->[0]};
    Check out perlref, perllol and especially perldsc for information about references and the ways you can use them.
Re: Re: Weird DBI/Array Use
by repson (Chaplain) on Jan 08, 2001 at 08:21 UTC
    If you only want one row then do use
    my @result = $dbh->selectrow_array("SELECT MAX(foo) FROM blah");

    If you just want one column then
    my @rows = @{ $dbh->selectcol_arrayref("SELECT id FROM blah") };

    Otherwise do a full $dbh->selectall_arrayref as salvadors suggests or use the full prepare, execute, fetchrow syntaxes like you were doing originally.

    For information on these syntaxes and more read up on the DBI docs.