in reply to Can a sub generate a closure from within itself?
Each time you call the anonymous sub constructor it creates a new closure already. What exactly do you mean by "adjust the type"? Something like this perhaps?
sub instantiator { my $state = shift; if( $state eq 'scalar' ) { return sub { ... something scalarly ... } } elsif( $state eq 'array' ) { return sub { ... an array of possibilities ... } } else { # hash return sub { ... make a complete hash of things ... } } }
Update: Aaah. You can overload &{}, so perhaps you could use that to do what you want (i.e. you return an object rather than a sub ref which has an overloaded &{} that examines whatever and then behaves differently).
package Foo; use overload "&{}" => \&deref; sub instatntiate { my $state = shift; # ... return bless { _original_code => sub { ... } } } sub deref { my $self = shift; ## examine $self and create $newsub using $self->{_original_code} $newsub->( @_ ); } package main; $f = Foo::instantiate( ... ); $f->( $a, $b, $c );
|
|---|