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


In reply to Re: Object attribute follower by kcott
in thread Object attribute follower by CSmatthieu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.