Perl 进阶知识(2)

Perl进阶知识点(2)

总结我在的自动化项目当中用到的PERL知识点

项目地址: https://gitee.com/lookingdreamer/RexDeploy_v1

1.0 全局变量 和 私有变量

  • 全局变量 our
  • 私有变量 my
  • 临时全局 local
our $global;
my $test;
$test = "ccccc";
sub test{
    my $test = "aaaa";
    $global = "bbbbb";
}

test;
print $test ."\n\r".$global;

使用变量必须用关键词限定它
our: “把名字限于某个范围“,其实就是明确声明一个”全局变量”,虽然是在某个模块或者函数里面定义的,外面的也可以访问,如果已经声明过了,再次用”our”,表示此处用的是全局的那个,不是同名的私有或者局部变量
my: “把名字和值都限于限于某个范围”,简单说,就是只能本层模块或者函数可以看到这个变量,高一层的或者低一层的都看不到的
local: “把值局限于某个范围”,也有叫”动态词法范围”,有点不好懂。我的理解,就是本层和本层下层的函数可以看到本层的变量,但是本层上一层的不可以。到底范围是多少,不仅取决于本层的函数,还要看下一层的程序长度和深度,所以叫”动态范围”

2.0 数组

2.1 数组长度

my $len=@ids;

2.2 判断数组是否存在元素

grep 判断数组中是否含有元素,存在就返回true 不存在返回false
格式: grep /^元素$/, @allow_env_array

my @allow_env_array = split(",",$allow_env);
if ( ! grep /^$env$/, @allow_env_array) {
    $args{"code"} = 3;
    $args{"msg"} = "env:$env must in ($allow_env)";
    return \%args;
}

2.3 删除数组最后一个元素

pop @keysArray;

2.4 数组的增加/删除/修改/查询

  • 增加:
    从后面追加: push @app_key_array,$app_key;
    从前面追加: unshift @app_key_array,$app_key;
  • 删除:
    删除索引为$deleteIndex的值: splice(@shared, $deleteIndex, 1)
    删除最后一个元素: pop @app_key_array
  • 修改:
    为数组赋值: $app_key_array[0] = "test";
  • 查询:
    根据循环查询所有数据
for my $key (@list){
    print $key;
}

2.5 数组转hash

my @keys = ('test','testa');
my %vars = map { $_ => 1 } @keys; 

3.0 Hash

3.1 hash判断是否存在key

my @keys = ('test','testa');
my %vars = map { $_ => 1 } @keys; 
......
if (exists($vars{$kv})){     
    ......
}else{
    Rex::Logger::info("关键字($kv)不存在","error");
}

3.2 删除hash中的key

delete $hash_pids{$kid}; 

4.0 函数

4.1 返回值问题

当返回数组或者hash的时候,请加\

return \%config;

5.0 条件

5.1 数值和字符串判断

数值用 == ,字符串用 eq

my ($env,$local_name) = @_;
my %args;
if ( "$env" eq "") {
    $args{"code"} = 1;
    $args{"msg"} = "env is must be not null";
    return \%args;
} 

6.0 循环

6.1 示例

select 等待,可以精确到毫秒;第4各参数可以是浮点数

 for (my $var = 1; $var <= 10 ; $var++) {
     select(undef, undef, undef, 1);
 }

7.0 MYSQL

7.1 mysql使用案例

注意点: 我一般设置超时时间很长,然后就是使用原生语句查询的时候最好设置utf8的编码

sub query {
    my ($env,$sql) = @_;
    if ( "$sql" eq "" ) {
        Rex::Logger::info("SQL不能为空","error");
        return;
    }
    my $dbh = init($env);
    $dbh->do('set SESSION wait_timeout=72000');
    $dbh->do('set SESSION interactive_timeout=72000');
    $dbh->do("SET NAMES utf8"); 
    my $sth = $dbh->prepare($sql);
    $sth->execute() or die( $sth->errstr );
    my @return;
    while ( my $row = $sth->fetchrow_hashref ) {
      push @return, $row;
    }    
    $sth->finish();
    $dbh->disconnect();
    return @return;
};

7.2 几个重要的参数

mysql_auto_reconnect: 自动重连很重要

$dbh->{RaiseError } = 1;
$dbh->{AutoCommit } = 1;
$dbh->{mysql_auto_reconnect} = 1;

8.0 文件和目录

8.1 遍历目录判断文件是否存在

my @Array ;
if (is_dir($randomDir)) {
    opendir DIR, ${randomDir} or die "打开目录失败";
    my @filelist = readdir DIR;
    foreach my $file (@filelist) {
        if (  $file =~ m/.hash$/ ) {
           my $hashFile =  $randomDir."/".$file ;
           Rex::Logger::info("read file: $hashFile");
           if ( is_file($hashFile) ) {
              my $hash = retrieve($hashFile);
              push @Array,$hash;
           }else{
              Rex::Logger::info("read file : $hashFile is not exist","error");
           }

        }
    }       
}

8.2 文件和目录存在判断

e: 文件是否存在
f: 文件是普通文件
d: 文件是目录

8.3 文件操作

  • 查询:

一行行处理

#>> 追加写入      >重新写入         <只读方式打开
open f,"<test.txt";  # 文件不存在创建
print f "$var\n";
close f; 

多行输出为一个数组

open(DATA,"<import.txt") or die "无法打开数据";
@lines = <DATA>;
print @lines;    # 输出数组内容
close(DATA);
  • 写入:
#>> 追加写入      >重新写入         <只读方式打开
open f,">>test.txt";  # 文件不存在创建
print f "$var\n";
close f; 
  • 删除:
#>> 追加写入      >重新写入         <只读方式打开
open f,">test.txt";  # 文件不存在创建
print f "$var\n";
close f; 
  • 修改:
#>> 追加写入      >重新写入         <只读方式打开
open f,">test.txt";  # 文件不存在创建
print f "$var\n";
close f; 
  • 修改权限
    chmod (mode , fileList)
  • 重命名
    注:创建新文件,旧文件删除,如果已存在newFileName文件则覆盖 。成功返回1
    rename (fileName, newFileName)
  • 删除文件
    unlink(filelist)
  • 文件复制
use File::Copy ;
use strict ;
copy("1.txt","2.txt")||warn "could not copy files :$!" ;

-文件移动

use File::Copy ;
use strict ;
move("1.txt","2.txt")||warn "could not move files :$!" ;

8.4 目录操作

  • 创建目录
    mkdir('d:\test',0755)||die "can't create directory: $!" ;
  • 删除目录
    rmdir('d:\perl\wzj')||die "can't remove diretory: $!";
  • 在某一目录内找指定文件
use strict ;
use File::Find ;
sub wanted{
  if ($_ eq "311.txt"){
      print $File::Find::name ;
      print "\n" ;
  }
}
find \&wanted ,"d:/";
  • 列出指定目录下所有的文件,包含子目录的内容
use strict ;
use File::Find ;
sub wanted{
   if (-f $File::Find::name){    #判断传入的是文件而不是目录。
      print "remove $File::Find::name ";
      print "\n";
    #  unlink $File::Find::name ;
   }
}
find \&wanted,'E:\nero\Content' ;

猜你喜欢

转载自blog.csdn.net/weixin_42914965/article/details/81539951