Perl 分类中的最新日记

DBD-mysql安装出错处理

| 暂无评论 | 暂无引用通告
mysql安装在/usr/local/下

perl Makefile.PL --mysql_config=/usr/local/mysql/bin/mysql_config --testuser=root --testpassword=s3kr1t
make
make test
出现以下错误:
PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/00base....................String found where operator expected at t/00base.t line 20, near "BAIL_OUT "Unable to load DBI""
        (Do you need to predeclare BAIL_OUT?)
String found where operator expected at t/00base.t line 21, near "BAIL_OUT "Unable to load DBD::mysql""
        (Do you need to predeclare BAIL_OUT?)
syntax error at t/00base.t line 20, near "BAIL_OUT "Unable to load DBI""
syntax error at t/00base.t line 21, near "BAIL_OUT "Unable to load DBD::mysql""
BEGIN not safe after errors--compilation aborted at t/00base.t line 22.
# Looks like your test died before it could output anything.
t/00base....................dubious
        Test returned status 2 (wstat 512, 0x200)
DIED. FAILED tests 1-6
        Failed 6/6 tests, 0.00% okay
t/10connect.................Use of uninitialized va
lue in concatenation (.) or string at t/10connect.t line 20.
skipped
        all skipped: ERROR:  Can't continue test
t/20createdrop..............Use of uninitialized value in concatenation (.) or string at t/20createdrop.t line 19.
skipped
        all skipped: ERROR: . Can't continue test
t/25lockunlock..............Use of uninitialized value in concatenation (.) or string at t/25lockunlock.t line 23.
skipped
        all skipped: Can't connect to database ERROR: . Can't continue test
t/29warnings................skipped
        all skipped: ERROR: install_driver(mysql) failed: Can't load '/usr/local/DBD-mysql-4.008/blib/arch/auto/DBD/mysql/mysql.so' for module DBD::mysql: libmysqlclient.so.16: cannot open shared object file: No such file or directory at /usr/lib64/perl5/5.8.5/x86_64-linux-thread-multi/DynaLoader.pm line 230.
t/30insertfetch.............Use of uninitialized value in concatenation (.) or string at t/30insertfetch.t line 18.
skipped
        all skipped: ERROR: . Can't continue
test
t/31insertid................Use of uninitialized value in concatenation (.) or string at t/31insertid.t line 18.
make: *** [test_dynamic] Interrupt

从这里找到出错的原因
http://mail.pm.org/pipermail/za-pm/2008q4/000320.html


|> Ok, the problem seems to be your version of Test::More. Upgrade it to
|> Test-Simple-0.80 and try the tests again:


升级Test-Simple

make test
继续出错
Can't load '/usr/local/DBD-mysql-4.008/blib/arch/auto/DBD/mysql/mysql.so' for module DBD::mysql: libmysqlclient.so.16:

ln -s /usr/local/mysql-5.1.30-linux-x86_64-glibc23/lib/libmysqlclient.so.16 /usr/lib64/

make test

测试顺利通过

另外还可以参考这篇文章
http://blog.c1gstudio.com/archives/183

使用Perl进行web制表

| 暂无评论 | 暂无引用通告
ChartDirector
http://www.advsofteng.com/
下载地址
http://www.advsofteng.com/download.html

安装ChartDirector
使用
perl -V
得到perl的@INC
将lib下的内容copy到INC的任一路径中

cd ChartDirector
cp -rf lib/*  /usr/lib/perl5/5.8.5/
如果自己定制目录的话,在编写脚本时,可在脚本头部加如下代码:
如:
use lib "/home/supersun/ChartDirector/lib/";


chart_create.pl


用法:
chart_create.pl  -f 数据文件 -m 图表类型 -t 图表标题 -p 图片文件名 -x X轴标题 -y Y轴标题
图表类型为:
bar 柱状图
line    曲线图
数据文件格式:
date                    host1     host2     host3     host4     host5     host6     host7     host8
20090101                3031132 3253513 3035196 3130065 3323986 3024694 3076513 3287113
20090102                3610310 3545421 3332149 3862804 3352384 3361875 3341946 3412295
20090103                3756983 3815154 3997797 3941998 3760445 3730529 3721120 3672436
20090104                3926538 3875646 3902116 4038819 4058506 3886227 3846330 4052068
20090105                3905990 4000435 3936811 3863121 3843673 3844999 3786345 3868149

#!/usr/bin/perl
#chart_create.pl
#author: supersun06@gmail.com
#url:  http://supersun.biz
use strict;
use lib dirname($0);

use perlchartdir;
use Getopt::Std;

sub line_grap;
sub bar_grap;
sub usage;

my %opts;
getopt('fmtpxy',\%opts);

my $file=$opts{f};
my $mode=$opts{m};
my $title=$opts{t};
my $png_file=$opts{p};
my $x_title=$opts{x};
my $y_title=$opts{y};

$x_title="X" if $x_title eq '';
$y_title="Y" if $y_title eq '';
usage unless $mode eq "line" || $mode eq "bar";
usage if  -z $title || -z $png_file;
die "$file isn't exsit\n" unless -f $file;



my $data={};
open FD,$file;
my @entries=<FD>;
my $head=[];
@{$head}=split /\s+/,$entries[0];
foreach my $entry (@entries){
        chomp $entry;
        my @utils=split /\s+/,$entry;
        foreach my $i (0..scalar(@$head)-1){
                push @{$$data{$$head[$i]}},$utils[$i];
        }
}
if($mode eq "bar"){
        bar_grap($png_file,$title,$x_title,$y_title,$head,$data);
}else{
        line_grap($png_file,$title,$x_title,$y_title,$head,$data);
}




sub usage {
        print "$0 -f datafile -m line|bar -t graph_title -p image_name -x x_title -y y_title\n";
        exit;
}

sub line_grap {
        my ($file,$head,$x_title,$y_title,$lable,$data)=@_;

        my $x_lable_tag=shift @$lable;
        print "$x_lable_tag\n";
        shift @{$$data{$x_lable_tag}};
        my @corlor=(0xffff00, 0x00ff00, 0x9999ff, 0xff0000, 0x223366,0xff8800, 0xa0bdc4, 0x999966, 0x333366, 0xc3c3e6);

        my $c = new XYChart(1200, 400, 0xffffc0, 0x000000, 1);
        $c->setPlotArea(80, 50, 1100, 300, 0xffffff, -1, -1, 0xc0c0c0, -1);
        $c->addLegend(45, 12, 0, "", 8)->setBackground($perlchartdir::Transparent);
        $c->addTitle($head, "arialbd.ttf", 9, 0xffffff)->setBackground($c->patternColor([0x004000, 0x008000], 2));
        $c->yAxis()->setTitle($y_title);
        $c->xAxis()->setTitle($x_title);
        $c->yAxis()->setLabelFormat("{value}");
        $c->xAxis()->setLabels($$data{$x_lable_tag});
        my $layer = $c->addLineLayer();
        foreach my $util (@$lable){
                my $col=shift @corlor;
                my $tag=shift @{$$data{$util}};
                $layer->addDataSet($$data{$util}, $col, $tag)->setDataSymbol($perlchartdir::SquareSymbol, 7);
        }



        #$layer->setDataLabelFormat("{value}");
        $c->makeChart("$file")
}

sub bar_grap {
        my ($file,$head,$x_title,$y_title,$lable,$data)=@_;
        my $x_lable_tag= shift @$lable;
        print "$x_lable_tag\n";
        shift @{$$data{$x_lable_tag}};

        my @corlor=(0xffff00, 0x00ff00, 0x9999ff, 0xff0000, 0x223366,0xff8800, 0xa0bdc4, 0x999966, 0x333366, 0xc3c3e6);

        my $c = new XYChart(1200, 400);
        $c->addTitle($head, "", 10);
        $c->setPlotArea(80, 50, 1100, 300, 0xffffc0, 0xffffe0);
        $c->addLegend(55, 18, 0, "", 8)->setBackground($perlchartdir::Transparent);
        $c->yAxis()->setTitle($y_title);
        $c->xAxis()->setTitle($x_title);
        $c->yAxis()->setTopMargin(20);
        $c->xAxis()->setLabels($$data{$x_lable_tag});
        my $layer = $c->addBarLayer2($perlchartdir::Side, 7);
        foreach my $util (@$lable){
                my $col=shift @corlor;
                my $tag=shift @{$$data{$util}};
                $layer->addDataSet($$data{$util},$col, "$tag");
        }
        $c->makeChart("$file")
}

运行
perl chart_create.pl -f data -m line -t "a test " -p line.png -x date -y pv
perl chart_create.pl -f data -m line -t "a test" -p bar.png -x date -y pv
bar.png

line.png
Windows下使用方法:
下载ActivePerl
http://www.activestate.com/activeperl/features/
下载ChartDirector,平台选择windows
http://download2.advsofteng.com/chartdir_perl_win32.zip
下载脚本,将其存放到D:\perl\chartdir_perl_win32\ChartDirector\lib\chart_create.pl
chart_create.pl
perl chart_create.pl -f c.txt -m bar -t "a test " -p line.png -x date -y pv
运行命令即可。





awstats按日报表日历界面

| 暂无评论 | 暂无引用通告
脚本:perl_calendar.pl
使用模块:HTML::Calendar::Simple
安装模块:
cpan HTML::Calendar::Simple
如手动,需安装以下两个包:
Date-Simple
HTML-Calendar-Simple
将其存放在cgi目录中添加可执行权限

#!/usr/bin/perl -w
#Script Name: perl_calendar.pl
#author: supersun@gmail.com
#url: http://supersun.biz
use strict;

use HTML::Calendar::Simple;
use CGI qw/:all/;

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime;
my $awstats_path="/awstats/awstats.pl";
print header(-charset=>'gbk');
if(param('host')){
        $year+=1900;
        $mon++;
        my $host=param("host");
        my $link_tag=1;

        print start_html("awstats for $host");
        print h1({-align=>"center"},"awstats for $host"),hr({-align=>"center"});

        print "<table border='1' align='center'>\n";
        print "<tr>\n";
        foreach my $month (01..12)
        {
                print "<tr>\n" if($month =~ /5|9/);
                print "<td valign='top'>";
                my $cal = HTML::Calendar::Simple->new({ 'month' => $month, 'year'  => $year});

                foreach my $day (1..31){
                        my $location=$awstats_path."?config=$host&databasebreak=day&day=$day&month=$month";
                        if($month eq $mon && $day eq $mday ){
                                $link_tag=0;
                                $cal->daily_info({'day'      => $day, 'pin_up'=>'now'});
                        }
                        if( $link_tag eq 1){
                                $cal->daily_info({'day'      => $day, 'day_link' => $location});
                        }else{
                                $cal->daily_info({'day'      => $day });
                        }
                }
                my $html = $cal->calendar_month;

                print $html;
                print "</td>\n";
                print "</tr>\n" if($month =~ /4|8/ );

        }
        print "</tr></table>\n";
}else{
        print "You must input a host: ",start_form,"Host: ",textfield('host'),submit,end_form;
}
print end_html;
界面如下:
perl_calander.jpg的缩略图
使用awstats按日分析参考:
http://www.chedong.com/blog/archives/001293.html


inotify监控文件的更改

| 暂无评论 | 暂无引用通告
      脚本读取目录列表(脚本所在目录下的db.conf),将目录添加到inotify监控中,被监控目录下新创建的目录也会被添加到监控中去.被监控目录下创建的文件或文件内容被更改后,脚本以日志的方式文件名发送给本机的syslog。脚本发送日志时使用的facility为local2,priority为info,进程名为inotifyd。
      脚本的内容如下:
#!/usr/bin/perl

use strict;
use Event;
use Linux::Inotify2;
use POSIX;
use IO::File;
use Sys::Syslog qw(:DEFAULT setlogsock);

my $script_dir="/opt/";
our $CONF_FILE=$script_dir."db.conf";


#For Daemon
###################################################
sub daemonize {
        chdir "/";
        open STDIN, "</dev/null";
        open STDOUT, ">/dev/null";
        open STDERR, ">&STDOUT";
        defined(my $pid=fork) or die "Can't fork: $!\n";
        exit if($pid);
        POSIX::setsid() or die "Can't start a new session: $!";
        umask 0;
}

sub add_watch {
        my ($inotify,$log_file)=@_;
        open FH,$log_file;
        while(<FH>){
                my $file=$_;
                chomp $file;
                $inotify->watch ($file, IN_ALL_EVENTS, \&mywatch)
        }
        close FH;
}

####################################################
                         
&daemonize;

my $ident="inotify";
my $logopt="ndelay";
my $facility="local2";
my $priority="info";
openlog $ident, $logopt, $facility;       # don't forget this


our $INOTIFY_OBJECT=new Linux::Inotify2;
Event->io (fd => $INOTIFY_OBJECT->fileno, poll => 'r', repeat => 1, cb => sub { $INOTIFY_OBJECT->poll });

Event->signal (signal => 'HUP',cb => \&re_conf);

add_watch($INOTIFY_OBJECT,$CONF_FILE);

Event::loop;

sub re_conf{
        add_watch($INOTIFY_OBJECT,$CONF_FILE);
        Event::loop;
}


sub mywatch {
        my $e = shift;
        my $PATH= $e->fullname;
        my $MASK= $e->mask;
  
  
        if($e->IN_ISDIR){
         if($e->IN_CREATE){
            $INOTIFY_OBJECT->watch($PATH,IN_ALL_EVENTS, \&mywatch);
                    return;
        }
        }else{
            if($e->IN_MODIFY || $e->IN_CREATE){
                    syslog($priority,$PATH);
                    return
            }
    }
}

例如,我们需要监控/data下的目录:

将脚本保存在/opt下命名为inotifyd.pl
安装脚本使用的模块:
cpan Event
cpan Linux::Inotify2
cpan Sys::Syslog
设定脚本所在目录
vi /opt/inotifyd.pl
my $script_dir="/opt/";
检测脚本是否可运行:

[supersun@supersun.biz opt]$ perl -c inotifyd.pl
inotifyd.pl syntax OK


配置syslog.conf,添加以下的行:
local2.*                                                /var/log/inotify.log
或将日志发送给日志主机loghost
local2.*                                                @loghost

更改message行:
auth,authpriv,cron,daemon,kern,lpr,news,syslog,user.info;mail.none;authpriv.none;cron.none              /var/log/messages
不然的话inotify的日志也会发送至/var/log/messages中去

创建需要监控的目录的列表:
find /data -type d >/opt/db.conf

启动脚本
perl inotifyd.pl

脚本接收HUP信号,重新读加监控目录列表,将上次未加载的录添加到监控中。

如果目录列表很长的话,使用top查看进程状态,态状为R时,inotifyd.pl正在加载目录列表,状态S时,脚本已开始监控。

查看/var/log/inotify.log(根椐自己/etc/syslog.conf中的配置)中的日志输出。

Mar 20 15:36:28 supersun.biz inotify: /data/hello.txt

syslog使用的udp协议发送日志,如何使syslog监听udp的514端口可以参考将防火墙的日志发送给日志主机
syslog-ng可以使用tcp协议发送日志,也可以通过加密的方式发送日志

 

Perl:将日志发送给syslog

| 暂无评论 | 暂无引用通告
使用模块Sys::Syslog

将日志发送给本机

#!/usr/bin/perl -w
use strict;

use Sys::Syslog qw(:DEFAULT setlogsock);

my $ident="inotify";  #进程命
my $logopt="ndelay";
my $facility="local2";  #设备名
my $priority="info";    #日志级别
openlog $ident, $logopt, $facility;       
syslog($priority,"hello"); #记入日志
closelog;


将日志发送到日志主机

#!/usr/bin/perl -w
use strict;

use Sys::Syslog qw(:DEFAULT setlogsock);

my $ident="inotify";  #进程命
my $logopt="ndelay";
my $facility="local2";  #设备名
my $priority="info";    #日志级别
setlogsock('udp','log.supersun.biz');
syslog($priority,"hello"); #记入日志
closelog;

如果使用tcp协议传输日志:
setlogsock('tcp','log.supersun.biz');
同时,更改/etc/services
将514/tcp的服务名改为syslog

log option的几个可设定的值

    * cons - This option is ignored, since the failover mechanism will drop down to the console automatically if all other media fail.
    * ndelay - Open the connection immediately (normally, the connection is opened when the first message is logged).
    * nofatal - When set to true, openlog() and syslog() will only emit warnings instead of dying if the connection to the syslog can't be established.
    * nowait - Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process, so this option has no effect on Linux.)
    * perror - Write the message to standard error output as well to the system log.
    * pid - Include PID with each message.

syslog记入的日志格式

Mar 18 13:17:13 host1.supersun.biz inotify: test message
时间  接收到日志的时间
主机名  发送日志的主机
进程名 前面定义的$ident
日志内容

相关文章

使用syslog-ng配置日志主机
将防火墙的日志发送给日志主机

用逗号替换换行符

| 暂无评论 | 暂无引用通告
本来想使用awk的,可是老半天没想出来,笨一点,先将活干完:
perl -e '$file=shift;
open FD,$file;
undef $/;
$c=<FD>;
$c =~ s/\n/,/g;
print $c;
close FD;' filename

后来查了一下awk的用法:

awk 'BEGIN {RS=""} {gsub("\n",",");print $0}' filename

再来一个Perl的:

perl -pe "$/='';s/\n/,/g " filename

看这里:http://www.stonehenge.com/merlyn/UnixReview/col01.html

暴晕!

Perl读取Excel表格中的数据

| 暂无评论 | 暂无引用通告
#!/usr/bin/perl -w
use strict;
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::FmtUnicode;

#创建一个表格解析对象
my $oExcel = new Spreadsheet::ParseExcel;
die "You must provide a filename to $0 to be parsed as an Excel file" unless @ARGV;
 #设定格式转码
my $oFmtC = Spreadsheet::ParseExcel::FmtUnicode->new(Unicode_Map=>"CP936");
#解析文件,文件名为传给脚本的第一个参数
my $oBook = $oExcel->Parse($ARGV[0],$oFmtC);
#表格文件中的表序
my $iSheet=0;
#获得表格文件的第一张表
my $worksheet=$oBook->{Worksheet}[$iSheet];
#获取指定表中的值 列序、列序的始值为0
my $value=$worksheet->{Cells}[行序][列序]->Value;

另外看这里:
http://blog.chinaunix.net/u/14845/showart_80678.html
http://www.ibm.com/developerworks/cn/linux/sdk/perl/culture-8/index.html

使用Perl生成excel表格

| 暂无评论 | 暂无引用通告
use Encode 'decode';
use Spreadsheet::WriteExcel;

#创建一个文件

my $workbook = Spreadsheet::WriteExcel->new("perl.xls");
添加格式
$workbook->add_format('border'=>5);
#创建一个工作表
# Add a worksheet
$worksheet = $workbook->add_worksheet("sheetname");  #如果是中文表名,使用decode('gb2312',"表名")
$worksheet->set_column('A:B', 13);
#  Add and define a format
#设定格式

my $format = $workbook->add_format(); # Add a format
    $format->set_align('left');
    $format->set_font('AR PL ShanHeiSun Uni');

#写入表格:
#此处的内容是中文,需要转码
  $worksheet->write(行序,列序,decode('gb2312',"数据"),格式);

此处的行序,列序起始值为0

perl删除文件

| 暂无评论 | 暂无引用通告
使用unlink函数,如:
perl -e '$file=$ARGV[0];unlink $file' -- anaconda-ks.cfg
删除当前目录下的anaconda-ks.cfg

利用Tie::File可以将文件的内容看着是一个数组来操作,具体示例如下:

[supersun@supersun.biz perl]$ cat tie.pl

#!/usr/bin/perl -w

use strict;

 

use Tie::File;

 

my $file=shift;

my @arrary;

tie @arrary,'Tie::File',$file;

 

push @arrary,"hello";

在文件的结尾增加一行:hello

[supersun@supersun.biz perl]$ cat test

aaaaa

[supersun@supersun.biz perl]$ perl tie.pl  test

[supersun@supersun.biz perl]$ cat test

aaaaa

hello

[supersun@supersun.biz perl]$

 

    我使用这个模块的目的主要是用于处理inotify脚本生成的日志文件,因为之前一直使用logrotate及cron来实现文件的上传,cron的最小时间间隔是1分钟,间隔稍长了一点。

最新资源

  • IMG_1437.JPG
  • line.png
  • bar.png
  • perl_calander.jpg

关于此归档

这里是分类Perl中的最新日记。

上一个分类Life

下一个分类SysAdmin

首页归档页可以看到最新的日记和所有日记。