前言:
以下材料为 per l脚本学习过程中电子形式的记录,与大家共享。
1. defined 的使用(判断某个变量是否被赋值)。
$b="";
if((defined $b)==1)
{
printf("have original value\n");
}else {
printf("not init\n");
}
2. 通过 $#ARGV 判断 perl 脚本运行时是否带有参数。
cmd $#ARGV
./test.pl -1
./test.pl xx 0
./test.pl xx yy 1
3. 获取脚本的文件名称。
basename($0) 获取脚本文件的名称,没有路径信息、perl等。比如: perl ./aa/bb/c.perl 返回 c.perl
4. 环境变量的获取。
$ENV{AUTO_HOME}
5. 为什么有时候别人的脚本里出现 use strict ?
use strict; 可以检测出拼写类错误,$ENV{_}DENG等
6. 常见数据结构的访问。
$string = "string";
@array = qw(w,e,r,5);
%hash = (1=>q,3=>r);
printf("$#ARGV\n");
my $str = "string";
my @array = qw(w e r 5 y 0.0);
my %hash = (1=>5, r=>4, e=>6);
print $str."\n";
printf("\@array len is: [".@{array}."]\n");
printf("\@array content is: [@array] \n");
for(my $i=0;$i<@array;$i++)
{
printf("$i is $array[$i]\n");
}
while((my $k,my $v)=each(%hash))
{
printf("$k is for $v\n");
}
7. 读文件内容并显示。
8. 常用函数的示例。
9. 函数定义域之 --- 全局变量
函数定义域之 --- 继承变量
函数定义域之 --- 本地变量
10. pop函数的使用。
shift 函数的使用。
11. perl 跳过注释
next if ($_=~/^(s*#)/);
12.eval的用法
(1)try{} catch
eval {
1/0; # 这会做成 division by zero 的 die() 错误
}; # 留意这里是要分号的!
if ( $@ ) { # 这就是在 eval 发现抓到错了!
print "Some error happen!! $@" # 这样就可以得到错误的讯息
}
else {
print "All good!!"
}
13.perl 多线程开发
#!/bin/perl
use threads;
use Cwd;
use POSIX qw(strftime);
sub count
{
my $i;
my ($name) = @_;
my $current_time = strftime "%Y-%m-%d %H:%M:%S", localtime;
for ($i = 0; $i < 10; $i++)
{
print "$current_time $name $i\n";
system("python Open_B.py");
}
}
#创建第一批线程
my $thread_1_01 = threads->create('count', Thread_1);
my $thread_1_02 = threads->create('count', Thread_2);
# 等待第一批线程结束完成
$thread_1_01->join();
$thread_1_02->join();