IO::Socket に lvalue アクセサを追加する
package MySocket; use strict; use warnings; use base qw( IO::Socket::INET ); use Scalar::Util qw( refaddr ); { my $data_ref = {}; my @functions = qw( hogehoge1 hogehoge2 ); no strict 'refs'; # copy routines into IO::Socket for my $f (@functions) { *{"IO\:\:Socket\:\:$f"} = sub :lvalue { my $self = shift; my $data = shift; return unless defined $self; $data_ref->{ refaddr $self }->{$f}; }; } sub DESTROY { my $self = shift; my $refaddr = refaddr $self; delete $data_ref->{$refaddr} if exists $data_ref->{$refaddr}; $self->SUPER::DESTROY(@_); } } 1;
で
#!/usr/local/bin/perl use MySocket; my $socket = MySocket->new( ... ); $socket->hogehoge1 = 'hogehoge1'; print $socket->hogehoge1, "\n";
とかできるようになる。なんか他に良い方法あるのかな。