#!/usr/bin/env perl -l use strict; use warnings; my %data = ( A => { C => { D => 4, E => [ 22, 33 ], }, }, B => { C => { D => [ 44, 55 ], E => 5, }, }, ); my $get_value_code = sub { $_[0] }; my $is_ref_code = sub { ref $_[0] }; my @paths = ([qw{A C D}], [qw{A C E}], [qw{B C D}], [qw{B C E}], []); for (@paths) { if (generic_hash_logic(\%data, $_, $is_ref_code)) { print "Path [@$_] is a reference: not printed."; } else { print "Path [@$_] is a value: ", generic_hash_logic(\%data, $_, $get_value_code); } } sub generic_hash_logic { my ($hash, $path, $code) = @_; my $end = $hash; $end = $end->{$_} for @$path; $code->($end); } #### Path [A C D] is a value: 4 Path [A C E] is a reference: not printed. Path [B C D] is a reference: not printed. Path [B C E] is a value: 5 Path [] is a reference: not printed.