| ||
1. 变量
my $fruit = "apple"; #my定义的是局部变量;字符串定义
$fruit = "apple"; #定义的是全局变量
my %hash = (); #hash变量声明
my $Name = ""; #字符串变量声明
my @Steps = (); #数组变量声明
2. 数组
@arr = (); #数组定义并初始化
push(@arr, "element1"); #将“element1”放入数组
my $arrLength = scalar @arr; #数组长度
foreach my $ele (@arr) { #数组遍历
print("$ele\n");
}
for(my $i = 0; $i <@arr; $i++) { #数组遍历
print("$arr[$i]\n");
}
数组切片: @arr[10..200]
二维数组:
my @choice_list = (); #二维数组初始化
my @choice_list_tmp = ();
$tmp = "1.1 2.2 3.3 4.4";
@choice_list_tmp = split " ", $tmp; #得到一维数组
push @choice_list, [@choice_list_tmp]; #将数组 [@choice_list_tmp]作为二维数组的第一个元素
$tmp = "5.5 2.2 6.6 8.8";
@choice_list_tmp = split " ", $tmp;
push @choice_list, [@choice_list_tmp]; # [@choice_list_tmp]需要加[ ],不然会报错
#二维数组遍历
for($i = 0; $i< @choice_list; $i++){
my $k =0;
for($j = 0; $j < @{$choice_list[0]}; $j++){
$list = join(" " ,$choice_list[$k][0],$choice_list[$k][1]); #将数组中两个元素合并成字符串
if ($list eq $choice_list[$i][$j]) {
$tmp_string = 1;
}
}
}
3.hash(散列)
$hashExample{$key1} = 1;
$hashExample{$key2} = "apple";
$hashExample{$key3} = [@choice_list_tmp]; #hash键对应的值可以为数组,数组外必须有[ ]
my @arr2 = keys %hashExample; #得到hash中所有的键,并存入一个数组
my $length = keys %hashExample; #hash中键值对数量
@{$hashExample{$key3}}[0]; #当hash的value为数组时,数组元素的调用
hash遍历:
open(OF, ">$outFile"); #文件句柄,向outFile中写入内容
foreach my $key (keys %hashExample) {
print(OF "$hashExample{$key}\n");
}
close OF; #写入完成后要关闭文件
4. 函数定义(function define)
#传入参数为两个数组
sub common($) {
my ($arr1, $arr2) = (shift,shift); #传入参数是两个数组的地址,为指针型变量
my $count = 0;
for(my $i = 0; $i < @$arr1; $i++) {
for(my $j = 0; $j < @$arr2; $j++) {
if (@$arr1[$i] == @$arr2[$j]) {
$count += 1; last;
}
}
}
return $count;
}
my $var1 = &common(\@oriArr,\@NewArr);
#传入参数为一个数组
sub dealMissing($) {
my (@arr) = @_;
my %tmpHash = ();
foreach $ele (@arr) {
$tmpHash{$ele} = 0;
}
foreach $ele (@arr) {
$tmpHash{$ele} += 1;
}
return %tmpHash;
}
my %MissingSteps= &dealMissing(@stepNum);
&Classify($Layer, $Name, @TreeSteps);
#将数字存为6位浮点数
$arr[$i] = sprintf "%.6f", $arr[$i];
#判断数组中是否存在某个字符串,如果不存在,输出error
grep 存在为1,不存在为0
#!/usr/bin/perl -w
my @parameter = ("Name", "La", "CLA");
if((grep /'Name'/i, @parameter) == 0) {
print "ERROR: ruleName is not supported!!\n"; exit 0;
}
$key = "Name";
if((grep /$key/i, @parameter) == 0) {
#$key can't be written as '$key'
#if((grep /\b$key\b/i, @parameter) == 0) {
#如果编译报错Quantifier follows nothing in regex; marked by <-- HERE in m/? <-- HERE CLASS/ at......,可尝试\b$key\b
print "ERROR: ruleName is not supported!!\n"; exit 0;
}
连接字符串 (.)
$tmp_1 = $tmp_1 . " " . "good" . "string1";