1、Perl 调用环境中的命令, 如linux 命令,windows 的cmd 命令等,此处使用简单的反引号调用,可以捕捉命令的输出,且每次输出都带一个回车换行:
#!/usr/bin/perl
use strict;
sub main {
foreach (@INC) {
print "$_ : ".`ls $_`; # call ls command!
}
}
&main ();
2、 函数 localtime (), 返回本地时间的各项时间数据的列表, (seconds, minutes, hours, day of month, month, year, day of week, day of year, daylight savings time)
use strict;
use warnings;
use POSIx;
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
localtime (); # list context
my $now = scalar (localtime); # scalar context
$year += 1900;
$mon += 1;
3、 简单的脚本程序,ping一台主机,是否能在长时间内稳定的ping上。注意使用管理员权限运行。思路很简单: 连续的ping这台主机,如果不能ping上,就记录日志,如果能ping上,继续ping
使用到的模块:File::Log Net::Ping
#!perl
# author : ez
# date : 2015/3/5
# describe : test the host reachable and print
# the none reachable time;
use strict;
use warnings;
use Net::Ping;
use File::Log;
package Main;
# global
my $host = "127.0.0.1"; # the remote host
my $proto = "icmp"; # protocol to ping
my $logfile = "./log.txt"; # log file name
my $file = undef; # log file handle
my $pn = undef; # ping entity
sub _init_log_file {
$file = File::Log -> new ({
debug => 4,
logFileName => $logfile,
logFileMode => ">>",
dateTimeStamp => 1,
stderrRedirect => 1,
defaultFile => 1,
logFileDateTime => 0,
appName => "reachable.pl",
PIDstamp => 0,
storeExpText => 1,
msgprepend => '',
say => 1
});
return $file if $file;
undef;
}
sub main {
$pn = Net::Ping -> new ($proto);
$file = &_init_log_file;
die "i cannot open log file or init ping entity\r\n"
unless ($file || $pn);
while (1) {
if (! ($pn -> ping ($host, 2))) {
$file -> msg (2, "$host is not alive.");
}
}
}
END {
$file -> close () if $file;
$pn -> close () if $pn;
}
&main;
4、 perl here document: 从标记声明的下一行开始,一直到遇到标记为止的所有字符串,赋值给变量:
#! perl
use strict;
use warnings;
my $a = 100;
my $b = 20;
my $str = <<__end
hello $a;
hello $b;
this is @INC;
__end
;
print $str;
此处将保留<<__end到__end之间的字符串格式,当输出时,按此格式输出,省事!$a和 $b 都将扩展成值。注意 << 和 标记名称必须靠在一起,且结束标记下一行要加上分号,不能写在同一行,否则perl 解释器会认为结束标记包含分号。
5、 Strawberry Perl 在windows 7 输出中文:
#! perl
use strict;
use warnings;
use v5.14;
use utf8;
# use Encode qw(encode decode);
# use encoding "utf8", STDOUT => 'gbk';
sub test_chinese {
my $gb2312_str = "中国";
binmode (STDOUT, ':encoding(gbk)');
print $gb2312_str;
}
&test_chinese;
windows7 和 xp默认使用的是GBK编码中文,将之转码为GBK即可正常显示中文。 注: 文件编码是用notepad++ ,编码方式为UTF-8,不带BOM。