cpan关于Storable的例子

        use Storable qw(store retrieve freeze thaw dclone);

        %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);

        store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";

        $colref = retrieve('mycolors');
        die "Unable to retrieve from mycolors!\n" unless defined $colref;
        printf "Blue is still %lf\n", $colref->{'Blue'};

        $colref2 = dclone(\%color);

        $str = freeze(\%color);
        printf "Serialization of %%color is %d bytes long.\n", length($str);
        $colref3 = thaw($str);

用在socket上

client:

#!/usr/bin/perl
use strict;
use IO::Socket;
use Data::Dumper;
use Storable qw(store retrieve freeze thaw dclone);

my $lsocket=&nsock;

my %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
my $str = freeze(\%color);

print $lsocket $str;

$lsocket->shutdown(1);
while(<$lsocket>){
        print "$_";
  }
 

sub nsock(){
        return IO::Socket::INET->new(
PeerAddr=>'127.0.0.1',
PeerPort=>'4321',
Proto=>'tcp',
);
}

 

 

-----

server端

#!/usr/bin/perl
use strict;
use IO::Socket;
use Data::Dumper;
use Storable qw(store retrieve freeze thaw dclone);

my $lsocket=IO::Socket::INET->new(
LocalAddr=>'127.0.0.1',
LocalPort=>'4321',
Listen=>SOMAXCONN,
Proto=>'tcp',
Reuse=>1,
Timeout=>30,
);
#=cut
while(1){
        my $tmpsocket = $lsocket->accept;
        next unless defined($tmpsocket);
        while(<$tmpsocket>){
                my $colref3 = thaw($_);
                print Dumper $colref3;
        }
        $tmpsocket->shutdown(1);
        print "end print\n";
}
-------

结果:

[root@localhost socket]# perl server.pl
$VAR1 = {
          'Red' => '0.8',
          'Blue' => '0.1',
          'Black' => 0,
          'White' => 1
        };
end print

 linux-windows socket传中文字符会出现乱码

今天使用storable又发现一个问题,不知道是不是我哪里出错了

问题描述

my %color = ('Blue' => ‘aa’, 'Red' => 0.8, 'Black' => 0, 'White' => 1);

传这样的hash socket另一端解析不了。

建议使用JSON模块,很简单,还可以处理中文字符问题