sub count { my ($data, $fields) = @_; $fields = [$fields] unless ref $fields; my $count = {}; _dive( $count, $_, @$fields ) for @$data; return $count; } sub _dive { my ($ref, $obj, @path) = @_; my $targ = \$ref->{ $obj->{ shift @path } }; if (!@path) { $$targ++; return $ref } $$targ = _dive( $$targ, $obj, @path ); } print Dumper( count(\@array_of_objects, 'sex') ); print Dumper( count(\@array_of_objects, ['sex','occupation']) );