[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] REALLY spiffy typeglob code, but with a significant weakness




Sean McAfee wrote:
> 
> use Symbol;
> 
> sub special_handle {
>         my $file = gensym;
>         *$file = sub {
>                 my $filenum = ++${ *$file };
>                 open $file, ">file-$num" or die "Can't open file file-$num: $!\n";
>         };
>         *$file->();  # open initial file
>         $file;
> }
> 
> my $file = special_handle();
> print $file "This goes to file-1\n";
> *$file->();
> print $file "This goes to file-2\n";
> *$file->();
> # ...
> ----------------------------------------------------------------------

package File::Special;
use overload '++' => \&incr;

sub new {
    my $num = 1;
    open my $file, ">file-$num" 
        or die "Can't open file file-$num: $!\n";
    ${ *$file } = $num;
    bless $file => $_[0];
}
sub incr {
    my ($file) = @_;
    my $num = ++${ *$file };
    open $file, ">file-$num" 
        or die "Can't open file file-$num: $!\n";
    $file;
}

package main;

my $file = File::Special->new;
print $file "This goes to file-1\n";
$file++;
print $file "This goes to file-2\n";
__END__

Not quite as fun as saving the closure but overload is still fun.

-- 
Rick Delaney
rick.delaney@home.com

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe