Perl, "closure" using Hash -


I want to have a substrate as a member of a hash, which is capable of accessing other hash members.

For example

  sub setup {% a = (txt = & gt; "Hello World", print_hello = & gt; sub {print $ {txt}; }) Back% A} My% obj = Setup (); $ Obj {print_hello};  

Ideally this will produce "Hello World"

Edit

Sorry, I Failed to specify the requirement

I should be able to do this

$ obj {txt} = "bye";

and then output to $ obj {print_hello} bye

If you need to be able to modify the call code in a hash, you need to return the hash from the reference. This does what you asked:

  Use strict; Use warnings; Sub self_expressing_hash {my% h; % H = (msg = & gt; "Hello", express_yourself => sub {print $ H {msg}, "\ n"},); Return \% H; } My $ h = self_expressing_hash (); $ H & gt; {Express_yourself} - & gt; (); $ H- & gt; {Msg} = 'Bye'; $ H & gt; {Express_yourself} - & gt; (); However, this is a bizarre concoction - essentially, a data structure that includes some underlying behaviors seems like a  object  that you might find in your project's Should look into the O-O approach. 


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -