perl学习笔记(五)


#!/usr/bin/perl

use 5.010;

say "-----------FreezeThaw模块------------------------";
#将复杂结构编码成可以打印的ASCII字符串,使用者可以将编码后的字符串发送到文件、DBM文件、数据库。
#use FreezeThaw qw(freeze thaw);#加载freeze()和thaw()
=pod
$c = {
'even' => [2,4,6,8],
'odd' => [1,3,5,7]
};
$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 => [2,4,6,8,],
old => [1,3,5,7,]
};
#创建样例对象
$obj = bless {'foo' => 'bar'},'Example';
#$obj = bless $c,'Example';
$msg = Dumper($c,$obj);
#say $msg;
$n = eval($msg);
say $n->{'foo'};
#say $n->{'even'}[0];

say "-----------Storable模块------------------------";
use Storable;
$a = [100,200,{"name" => 'giggs'}];
eval{
store($a,'test.dat');#指向数据结构(根)的引用,文件名
};
say "error writing to file :$@" if $@;

$a = retrieve('test.dat');#完成相反的工作,给定文件名,返回数据结构的引用
say $a->[0];
say $a->[2]->{"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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值