Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Object attribute follower

by kcott (Archbishop)
on Apr 15, 2016 at 04:41 UTC ( [id://1160493]=note: print w/replies, xml ) Need Help??


in reply to Object attribute follower

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1160493]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (8)
As of 2024-04-24 10:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found