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
|
|---|