Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I idiomatically access the first element of a single element hash in Perl?

Tags:

hash

perl

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

like image 255
GeneQ Avatar asked Dec 04 '22 03:12

GeneQ


2 Answers

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.

like image 117
fork0 Avatar answered Jan 25 '23 23:01

fork0


Instead of fetchall_hashref if you're only getting 0/1 rows back why not do a selectrow_array or selectrow_hashref?

like image 37
beresfordt Avatar answered Jan 25 '23 23:01

beresfordt