perl学习笔记-2
#Example6 #数组(i堆栈)
#!/usr/bin/perl
@arry = qw/ a1 a2 b3 c4 d5 d6/; #声明一个堆栈
print "@arry" . "\n";
@ff = pop(@arry); #出栈(最后一个d6)
print "@ff" . "\n";
print "@arry" . "\n";
push(@arry, b6,d7); #入栈把b6和d7压进去(在结尾)
print "@arry" . "\n";
@ff = shift(@arry); #出栈(第一个a1)
print "@ff" . "\n"; #
print "@arry" . "\n";
unshift(@arry, d1,c1); #入栈把d1和c1压进去(在开头)
print "@arry" . "\n";
#Example7 #foreach 循环
#!/usr/bin/perl
foreach (1..10) {
print "I can count $_!\n"; # $_ perl内置变量
}
foreach $rack (qw/ 1 2 3 10/) { #也可以指定变量$rack,循环控制参数qw/ 1 2 3 10/
print "I can count $rack!\n";
}
@rack= qw/ 110 11 we esfd ef/; #还可以使用数组@rack
foreach $rack (@rack) {
print "I can count $rack!\n";
}
#Example8 #标量与列表及其上下环境
#!/usr/bin/perl
@rock = qw( tals dfkl dj yu sj ); #某种程度上可以简单理解为@是列表(数组、堆栈...),$是标量(变量、字符串、数字、Boolean...)
$rock = @rock; #取@rock列表长度
print "@rock" . "\n"; #输出列表@rock
print @rock; #去除中间空格输出@rock
print @rock . "\n"; #输出@rock的长度
print $rock . "\n"; #输出@rock的长度
print "$rock" . "\n"; #输出@rock的长度
print scalar @rock; #输出@rock的长度
@ar = ("1542","123","0452"); #这种写法和qw//一样的
$ar = scalar @ar; #取@ar列表长度
print "@ar\n"; #输出列表@ar
$ar += 67; #对$ar进行加法操作
print "$ar\n"; #输出$ar的值
@ar = sort @ar; #对@ar进行排序(不是按照数值大小,而是按照ASCII码排序)
print "@ar\n"; #输出列表@ar
print @ar; #
#Example9 #子程序的调用
#!/usr/bin/perl -w #输出警告信息
sub sum { #定义子程序sum,该程序将会被覆盖
print "I'm sub_sum!\n"; #表明身份
$ff + $dd; #将计算$ff和$dd的和作为子程序的返回
}
$ff = 3;
$dd = 5;
$aa = ∑ #调用子程序sum,并将其返回值赋值给$aa
print "\$SUM is $aa.\n"; #输出结果
print "\$ff is $ff.\n";
sub sum { #重新定义子程序sum,该子程序将覆盖上面的sum
$ff = $ff + $dd; #计算$ff和$dd的和,赋值给$ff
$ff + $dd; #计算$ff和$dd的和,这个语句不是最后一条,
#执行结果不会作为子程序的返回,计算结果会被抛弃
print "I'm sub_sum!\n"; #print 语句执行的结果作为返回值(如果没有后面这句)
$ff = $ff + $dd; #将$ff和$dd的和相加后赋值给$ff,并将后来的$ff作为返回值
}
$aa = 3 * ∑ #调用子程序sum #调用子程序sum,并将其返回值赋值给$aa
print "\$SUM is $aa.\n"; #输出结果
print "\$ff is $ff.\n";
#Example10 #哈希数据
#!/usr/bin/perl
$family_name{"fred"} = "yu";
$family_name{"yu"} = "QQ";
$family_name{"QQ"} = "yu";
foreach $person (qw< fred yu QQ >) {
print "I've heard of person $family_name{$person}.\n";
}
$foo = "Q";
print $family_name{ $foo . "Q" }."\n";