perl脚本如果长时间不使用,一些语法会忘记,在此记录一些以往使用过的语法,以便以后写perl脚本时可以快速唤醒自己的记忆。
引用:骏马金龙 https://www.cnblogs.com/f-ck-need-u/p/9512185.html (骏马金龙博客还有很多Linux Shell Python 内容)
菜鸟教程 https://www.runoob.com/perl/perl-intro.html
- perl将perl命令行的参数列表放进数组ARGV(@ARGV)中。既然是数组,就可以访问($ARGV[n])、遍历,甚至修改数组元素
- ARGV数组分三种情况收集:
perl x.pl a b c
方式运行时,脚本名x.pl之后的a b c
才会被收集到ARGV数组./x.pl a b c
方式运行时,a b c
才会被收集到ARGV数组perl -e 'xxxxx' a b c
方式运行时,a b c
才会被收集到ARGV数组需要区分ARGV变量和ARGV数组:
$ARGV
表示命令行参数代表的文件列表中,当前被处理的文件名@ARGV
表示命令行参数数组$ARGV[n]
:表示命令行参数数组的元素ARGV
:表示<>
当前正在处理的文件句柄
ARGV使用:
#!/usr/bin/perl
use strict;
use warning;
@ARGV=qw(lic_cfg.txt); ##读取当前目录下的lic_cfg.txt
while(<>){ ##遍历打印lic_cfg.txt每行内容
pirnt "I saw $_";
}
@数组使用:
open LIST1, "<list1.txt";
open LIST2, "<list2.txt";
my @list1_q;
my $tc;
my $ture;
while(<LIST1>){
chomp;
push(@list1_q,$_); ##数组push
}
while(<LIST2>){
chomp;
if($_ =~ /^$/) {next;} ##空行跳过
$tc=$_;
$ture=0;
foreach my $i (@list1_q){ ##foreach 遍历数组 或者 foreach (@list1_q) 使用 $_ 代替 $i
if( $i eq $tc) {
$ture = 1;
}
}
if ($ture == 0){
print "$tc\n";
}
}
cp rm sed 等linux命令在perl中使用:
https://oomake.com/question/2977304 (如何删除perl脚本中的第一行文件)
https://www.runoob.com/perl/perl-process-management.html
https://www.cnblogs.com/f-ck-need-u/p/9691714.html
$list = "list.txt";
$tmp_list = 'tmp_'.$list; ## .连接符
`cp $list $tmp_list`; ## 直接通过 ` `调用linux复制命令
my @info, @info_2;
my $line = 'sed -n 1p list.txt'; ## sed 截取 list.txt第一行
@info = `$line`; ## ``调用 sed 命令
print @info; ## 打印数组
@info_2 = `ls`; ## ls 出当前目录下的内容,保存到数组中。
print @info_2; ##打印数组,一行一行打印
print scalar(@info_2)."\n"; ##打印数组size
`rm -rf $tmp_list`; ##rm 删除
`lmstat -a -c > .temp.txt`; ## 打印license信息
`sed -n "/$sim_begin_s/,/$sim_end_s/p" .temp.txt > .temp2.txt`;##通过sed截取部分信息
chomp($need_lic = `grep Engine .temp2.txt | wc -l `); ## 计算个数
perl中打印时间:
use POSIX qw(strftime);
print &cur_time."\n";
sub cur_time{
strftiime "%a_%d_%b_%H:%M:%S",localtime;
}
grep map 用法:
参考:https://blog.csdn.net/weixin_38927796/article/details/78248181
my @list = qw/2 4 5 7 23 26 32/;
my %ver = map{$list[$_],$_} 0..$#list; ## $#list表示@list中最后一个元素的编号,此处为6
while(my($key,$value) = each(%ver)){ ##哈希的遍历方法
print "$key => $value \n";
}
结果:
32 => 6
4 => 1
7 => 3
26 => 5
23 => 4
2 => 0
5 => 2
sort对哈希的值排序:
哈希:https://www.jb51.net/article/33905.htm
$log_hash; ##key:每个log的名字 value:log的总时间
my @key = sort{$log_hash{$a} <=> $log_hash{$b}} keys %log_hash;
foreach my $a(@key){ ##遍历数组 $a是hash的key
print(“log_name:$a, log_time:%6.2f hour”,($log_hash{$a}/60)) if $log_hash{$a}/60 < 100; ##%6.2f 小数,总共6位,2位小数
} ## if语句后置
find在perl中使用:
参考:https://blog.csdn.net/Holden_Liu/article/details/102645862
Data::Dumper使用: