Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Method for reducing tedium of transferring object properties to scalars

by shmem (Chancellor)
on Apr 21, 2017 at 22:00 UTC ( [id://1188591]=note: print w/replies, xml ) Need Help??


in reply to Method for reducing tedium of transferring object properties to scalars

The easiest way is creating a subroutine which takes the object as first argument, then an array of methods, calls those methods and returns something convenient - either a list (key/value pairs, or just the values) or a reference thereof:

sub get_props { my $obj = shift; # return just a list of values return ( map { $obj->$_ } @_ ); # return a list of key/value pairs return ( map { $_, $obj->$_ } @_ ); # to return references, just wrap the previous examples # into [] or {} as appropriate } my @meths = map { "get_value$_" } 1..3; # or whatever your methods are + really print "Values: @{[get_props($obj, @meths)]}\n"; # tweak to fit get_pro +ps()

Of course, that only works for method calls without arguments. If your methods need arguments, you'd tweak that sub to take named arguments (i.e. it is passed a list of key/value pairs where the key is the method, and the value is a reference to whatever the method takes), or a hash reference holding that. Don't use that stub as is. There's no check for error conditions etc.

update: It really depends on what your objects are, and what you are up to. If you are the Master of the Class/Package you are using, and if your objects are just scalar references (as any well behaved object should be), you could use overload to provide a shortcut:

package Object; use Hash::Util::FieldHash; use overload '%{}' => \&_get_props, fallback => 1; Hash::Util::FieldHash::fieldhash my %objects; sub new { my $class = shift; my $self = bless do { \my($x) }, $class; $objects{$self} = { prop1 => 'foo', prop2 => 'bar', blorf => sub {time}, }; bless $self, $class; } # getters/setters... sub get_prop1 { $objects{shift(@_)}->{prop1}; } # ... and so on sub _get_props { my $obj = shift; $objects{$obj}; +{ map { $_, ref $objects{$obj}->{$_} eq 'CODE' ? $objects{$obj}->{$_}->() : $objects{$obj}->{$_} } keys %{$objects{$obj}} } } 1; __END__
use Object; my $foo = Object->new; print "Values: ", join(", ", @$foo{qw(prop1 blorf)}),"\n"; __END__ Values: foo, 1492814598

Ah well... TIMTOWTDI - there are so much ways to wrap laziness into magic... ;-)

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (2)
As of 2024-04-20 06:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found