CSmatthieu has asked for the wisdom of the Perl Monks concerning the following question:

Hi all,

I need you'r help for a specific issue.

My problem :

I need to access to an attribute path into an object. Here a typical example :

my $objectWhenceFindPath; $objectWhenceFindPath->{here}->{an}->{hypothetical}->{path} = "some va +lue"; my @path = ("an", "hypothetical", "path"); my $currentPath = $objectWhenceFindPath->{here}; for my $index (0 .. ($#path - 1)) { $currentPath = $currentPath->{$path[$index]}; # Some logic, or not. Depend of script. } $currentPath ++;

At this time, I have not find any solutions to do this. Note as functional, the $objectWhenceFindPath is retrieved from an object subroutine.

Tested solution :

Many thanks to anyone able to purpose a solution.

Replies are listed 'Best First'.
Re: Object attribute follower
by Corion (Patriarch) on Apr 14, 2016 at 19:52 UTC

      Seem to be the solution. I'll try this tomorrow and come back for test results.

      Many thanks Corion .

Re: Object attribute follower
by kcott (Archbishop) on Apr 15, 2016 at 04:41 UTC

    G'day CSmatthieu,

    Welcome to the Monastery.

    Here's a highly contrived example of how you might pass a hashref (e.g. your object), an arrayref (e.g. your attribute path), and a coderef (e.g. your logic) to a single subroutine.

    #!/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); }

    Output:

    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.

    As I said, this is highly contrived and only intended to show a technique (i.e. it's not a solution).

    By putting your equivalent of &generic_hash_logic in a module, you can share it amongst all your scripts: no need to "create a subroutine for each one".

    — Ken