Sign in to PrePAN

Data::Lookup Neat lookup for complex data structures without any autovivification



package Data::Lookup;
use strict;
use warnings;
use Exporter 'import';

our @EXPORT = qw();
our @EXPORT_OK = qw(Reach);
our $VERSION = '0.1';

sub Reach {
    (!@ || ref $_[0] ne 'ARRAY' && ref $_[0] ne 'HASH') && die 'need hash or array ref as first argument';
    my $ptr = shift;
    while(@_) {
        if(!defined $ptr) {return wantarray ? (0,undef) : 0}

        my $key = shift;
        if($key =~ /^\d+$/) {
            if(ref $ptr ne 'ARRAY' || !exists $ptr->[$key]) {return wantarray ? (0,undef) : 0}
            $ptr = $ptr->[$key];
        elsif(substr($key,0,1) eq '%' && substr($key,1) =~ /^\d+$/) {
            $key = substr($key,1);
            if(ref $ptr ne 'HASH' || !exists $ptr->{$key}) {return wantarray ? (0,undef) : 0}
            $ptr = $ptr->{$key};
        else {
            if(ref $ptr ne 'HASH' || !exists $ptr->{$key}) {return wantarray ? (0,undef) : 0}
            $ptr = $ptr->{$key};
    return wantarray ? (1,$ptr) : 1;



Hey Perlers!

I've come up with my own module for lookuping data structures in one single line without autovivification.

Comprehensive examples could be found in test.t in the repository.

Here, I found some alternatives:

But I find my module more 'lightweight' and neat.

What do you think? Is it worth publishing?


What is the rationale of the % escape character? I think you can design your module without using it.

A minor style note: functions in perl modules are usually written in lowercase.
Percent sign in used as indicator that the 'accessor' of digits next to it is a hash key (such cases are real).

If one uses lowercase and underscores for simple subroutines from a module, then he can err, considering a call as call to subroutine defined in the script. Data::Lookup::Reach() is exported on-demand and is used as follows:
`use Data::Lookup 'Reach';
$ret = Reach($ds, ...);`
`use Data::Lookup;
$ret = Data::Lookup::Reach($ds, ...);`

Which doesn't leave any ambiguity. See Data::Dumper, it has simple subroutine Dumper() which is exported unconditionally.
You can get without the percent sign escaping if you check for the type of the current data structure while diving into it, i.e. access the data structure as a hash if ref ... eq 'HASH'. In fact, I would propose that you change your logic to always check the type of the current data structure, and not to use the format of the current path element.

For lowercase vs. uppercase: the possibility to err is there for all perl modules. The usual solution is to explicitly import nothing or a limited set of functions. Please don't look at Data::Dumper as a model for your module --- Data::Dumper is a very old module, and modern modules do not use uppercase functions anymore.

Please sign up to post a review.