I have script that gets some data using DBI's fetchall_hashref().
Usually it returns a hash ref like the following:
{ 1 => { id => 1 } }
However, I'm only interested in the value of the first item in the hash, which is the max value of a particular column. I know Perl hashes are not ordered, but luckily this particular query always return exactly 1 or 0 records (since this is a MAX() query).
But the code currently used to achieved that is really ugly:
$results->{(keys %{$results})[0]}->{'id'};
Is there a more elegant way to active this? (Without resorting to CPAN modules)
Clarification
I'm getting the hash from a data access layer that we use in house. Everything gets returned via fetchall_hashref(). I don't call the fetchall_hashref() itself, it's just how the data access functions are implemented internally, so I'm told. I'm a consumer of that returned data and it happens to be in the form of a hash. I'm looking for a more concise way, if it exists, to access the results of single return value queries
You can dereference the id
key of the first value in %$results
:
(values %$results)[0]->{id};
Normally, this would not be well defined since the ordering of values returned keys
or values
can be different even between runs on the same machine using the same perl
, but since you said %$results
can only ever contain one or zero elements, this is a valid method.
Instead of fetchall_hashref if you're only getting 0/1 rows back why not do a selectrow_array or selectrow_hashref?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With