举个栗子
my @items;
my @item;
my $stat_file = "/×××××/haproxy_stats.sock";
my $items_number;
sub get_haproxy_stat{
$items_number = `echo "show stat" | /usr/bin/socat $stat_file stdio|awk -F ',' 'NR==1 { print NF }'`;
for (my $i = 1; $i < $items_number; $i++){
$_ = `echo "show stat" | /usr/bin/socat $stat_file stdio|awk -F ',' '!/^\$/ { print \$$i }'`;
$items[$i-1] = $_;
}
foreach (@items){
@item = split('\n', $_);
foreach (@item){
$_ =~ s/^$/-/g;
if (@item[0] =~ /# /){
my @first_line = split(" ", @item[0]);
@item[0] = @first_line[-1];
}
}
my $state_format = " %-20s %-40s %-40s %-40s\n";
printf($state_format, @item[0], @item[1], @item[2], @item[3]);
}
}
perl的一些实用写法
- 格式化打印(以下表示格式化打印数组item中的前四项元素):
my @item = ("a", "b", "c", "d");
my $state_format = " %-20s %-40s %-40s %-40s\n";
printf($state_format, @item[0], @item[1], @item[2], @item[3]);
- 替换字符串中的某个字符(以下表示替换标量key中一个或多个“-”号为一个空格,且“-”号不位于开头或末尾):
$key =~ s/(?<=.)-+(?=.)/ /g;
- 判断字符串中是否含有某个字符或字符串(以下表示判断数组item中第一个元素中是否含有“# ”这个字符串):
if (@item[0] =~ /# /){
***;
}
- 在perl中执行shell命令(以下表示将shell命令下的echo “hello”结果存储到标量items中;”ls”等命令的结果需要用到数组来存储):
$items = `echo "hello"`;
- 遍历数组时,使用默认变量代替当前遍历值(以下表示使用“$_”代替了每次遍历的数组items中的元素):
foreach (@items){
$_ .= "\n";
}
- 根据特定字符分隔字符串(以下表示将标量string以空格分隔,分隔的结果存储在数组first_line中,此时first_line的内容为(“a”, “b”, “c”, “d”),再将first_line的最后一个元素赋值给数组item的第一个元素):
my $string = "a b c d";
my @first_line = split(" ", $string);
@item[0] = @first_line[-1];
备份地址