Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: elegant way of handling hash?

by g0n (Priest)
on Jan 19, 2006 at 10:22 UTC ( [id://524175]=note: print w/replies, xml ) Need Help??


in reply to elegant way of handling hash?

The context of your problem is still not entirely clear. Still, this example does what you ask for:

use strict; use warnings; my @methodcalls = qw (getExeName getTempName); my @getDataMethods = qw (getNameType); my $obj = Foo->new(); my %hash; my $counter=0; for my $call (@methodcalls) { $hash{"temp".$counter} = $obj->$call; $counter++; } for my $call (@getDataMethods) { $hash{"temp".$counter} = $obj->getData->$call; $counter++; } for (keys %hash) { print "$_\t $hash{$_}\n"; } package Foo; sub new { return bless \{}, shift; } sub getExeName { return "exename"; } sub getTempName { return "tempname"; } sub getData { return shift; } sub getNameType { return "nametype"; }

Note that the getData->getNameType call has to be treated separately from the simple method calls. If you have other (possibly more complex) chained methods, you'll have to adapt the code to handle those as well (unless someone can think of a better way?)

Update: As BrowserUK has said, the chained methods can be done with a string eval. It's a slow and ugly way of doing it, but it works:

use strict; use warnings; my $obj = Foo->new(); my %hash; my $counter=0; my @methodcalls = qw (getExeName getTempName getData->getNameType); for my $call (@methodcalls) { my $evalstring = "\$obj->$call"; $hash{"temp".$counter} = eval($evalstring); $counter++; } for (keys %hash) { print "$_\t $hash{$_}\n"; }

--------------------------------------------------------------

"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."

John Brunner, "The Shockwave Rider".

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-03-28 12:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found