perl学习笔记(五)
#!/usr/bin/perluse 5.010;
say "-----------FreezeThaw模块------------------------";
#将复杂结构编码成可以打印的ASCII字符串,使用者可以将编码后的字符串发送到文件、DBM文件、数据库。
#use FreezeThaw qw(freeze thaw);#加载freeze()和thaw()
=pod
$c = {
'even' => ,
'odd'=>
};
$obj = bless ('foo' => 'bar'), 'Example';
$msg = freeze($c,$obj);#数组和散列表必须用引用的形式传递
open(F,'>freeze')||die;
syswtite(F,$msg,length($msg));
($c,$obj) = thaw($msg);#thaw方法读取一个编码过的字符串并返回同样的标量变量列表
=cut
say "-----------Data::Dumper模块------------------------";
#转换成格式美观的perl代码,可以存储到文件中,以后可以进行eval操作
use Data::Dumper;
$c = {
even => ,
old =>
};
#创建样例对象
$obj = bless {'foo' => 'bar'},'Example';
#$obj = bless $c,'Example';
$msg = Dumper($c,$obj);
#say $msg;
$n = eval($msg);
say $n->{'foo'};
#say $n->{'even'};
say "-----------Storable模块------------------------";
use Storable;
$a = ;
eval{
store($a,'test.dat');#指向数据结构(根)的引用,文件名
};
say "error writing to file :$@" if $@;
$a = retrieve('test.dat');#完成相反的工作,给定文件名,返回数据结构的引用
say $a->;
say $a->->{"name"};
say "-----------DBI模块--交互式sql前端----------------------";
#错误代码和错误信息$DBI::err和$DBI::errstr
use DBI;
$dbname = 'zhbd';
$user = 'zhbd';
$password = 'zhbd!@#';
$dbd = 'Pg';
my $db = "DBI:Pg:database=zhbd";
$dbh = DBI->connect($db,$user,$password) ||
die "Errot connecting $DBI::errstr";
while(1){
print "SQL> ";
$command = <STDIN>;
last unless defined($command);
last if ($command =~ /^\s*exit/);
chomp($command);
$command =~ s/;\s*$//;
$sth = $dbh->prepare($command);
if ($DBI::err) {
say STDERR "$DBI:errstr";
next;
}
$sth->execute();
if ($DBI::err) {
say STDERR "$DBI:errstr";
next;
}
if($command =~ /^\s*select/i){
my $rl_names =$sth->{NAME}; #列名数组的引用
say "-----";
while(@results = $sth->fetchrow){#检索结果
say "@results";
say "***********************";
if ($DBI::err) {
say STDERR "$DBI:errstr";
last;
}
foreach $field_name (@$rl_names) {
printf "%10s: %s\n",$field_name,shift @results;
print "\n";
}
}
$sth->finish;
}
}
$dbh->commit;
页:
[1]