Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Object methods from hashy structures

by dirving (Friar)
on Dec 24, 2007 at 00:50 UTC ( [id://658819]=note: print w/replies, xml ) Need Help??


in reply to Object methods from hashy structures

If you want to avoid any external modules, you can do this pretty easily by manipulating the symbol table:
BEGIN { my @methods = qw/status deadline chasedate/; for my $method (@methods) { no strict 'refs'; # allow symbolic reference *$method = sub { return $_[0]->{$method} }; } }

There are two tricks here that you might not be familiar with. The first is using the * sigil to manipulate the symbol table. See perldata under the heading "Typeglobs and Filehandles" to learn more about this syntax, and perlmod to learn more about the workings of the symbol table.

The second trick is the creation of a closure. Using the sub { } notation creates an anonymous subroutine that "closes" over any lexical ("my") variables in the scope where it is defined. You can think of this as attaching the variables to the sub so that it can access them whenever it is called. In this case the sub carries the $method variable with it so that it knows which field of the hash to access when it is called. Search for "closure" in perlref to find out more about these.

-- David Irving

Replies are listed 'Best First'.
Re^2: Object methods from hashy structures
by jfrm (Monk) on Dec 24, 2007 at 08:33 UTC
    That's exactly what I was after, thank you. I appreciate all the enlightening suggestions but implementing new modules was a bit of sledgehammer to crack a nut. A 4 liner is much preferred!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2024-04-18 07:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found