in reply to Re^2: Ways to implement a closure
in thread Ways to implement a closure

I see. Well there you go, yet another way!

Nit: that code works in C (given some imagined Hash class), and the data does stick around:

Hash<...>* demonstration<...>(... a) Hash<...>* hash_ptr = new Hash<...>("demo_data", a); return new Hash<...>( "demonstration_data", hash_ptr ); }

I think you meant this:

sub demonstration { my %demonstration_data = ( demo_data => shift ); return { demonstration_data => \%demonstration_data, }; }

Which wouldn't work in C:

Hash<...>* demonstration<...>(... a) Hash<...> hash("demo_data", a); return new Hash<...>( "demonstration_data", \hash XXX BUG ); }

Replies are listed 'Best First'.
Re^4: Ways to implement a closure
by SpanishInquisition (Pilgrim) on Oct 18, 2004 at 19:50 UTC
    C does not have templates OR classes! (Not that this is a bad thing...)
      Oops, I often call C++ by the wrong name. But while the code was C++, the argument does work for C as well. Here's the C version of the C++ snippets:
      HASH* demonstration(void* p) HASH* hash_ptr = hash_new() hash_add(hash_ptr, "demo_data", p); HASH* outer_hash_ptr = hash_new(); hash_add(outer_hash_ptr, "demonstration_data", hash_ptr); return outer_hash_ptr; }

      and

      HASH* demonstration(void* p) HASH hash; hash_init(&hash); hash_add(&hash, "demo_data", p); HASH* outer_hash_ptr = hash_new(); hash_add(outer_hash_ptr, "demonstration_data", &hash); XXX BUG return outer_hash_ptr; }