perl学习笔记-3

#Example11 #哈希数列2
#!/usr/bin/perl

my %hash = ("a" => 1, "b" => 2, "c" =>3);
my @k = keys %hash;
my @v = values %hash;
print "@k\n";
print "@v\n";

while ( ($key, $value) = each %hash ) {
print "$key => $value\n";
}

foreach $key (sort keys %hash) {
$value = $hash{$key};
print "$key => $value\n";

}

#Example12 正则表达式:$_的简写
#!/usr/bin/perl

$_ = "yu qq QQ doo";
if (/a/) {
print "It has matchd!\n";
}
else {
print "It has not matchd!\n";
}

#Example13 #正则表达式:(.)\1 匹配连续出现的两个相同的字符
#!/usr/bin/perl

$_ = "yu qq QQ oo";
if (/(.)\1/) { #将会匹配qq、QQ、oo
#'\1'表示刚刚匹配过的字符
print "It matchd same character next to itself!\n";
}

$_ = "yabba dabba doo";
if (/y(....) d\1/) { #'\1'表示刚刚匹配过的字符,即(....)匹配到的东西
print "It matched the same after y and d!\n";
}

$_ = "yabba dabba doo";
if (/y(.)(.)\2\1/) { #将会匹配abba
print "It matched the same after y and d!\n";
}

#Example14 #正则表达式:\s 匹配换页、制表、换行、回车、空格
#\w 匹配字母数字下划线
#\d 匹配数字 ...
#!/usr/bin/perl

$_ = "Hello there, neighor";
if (/\s(\w+),/) { #匹配规则,先是一个空格,然后是一个单词,然后是一个","
print "The word was $1\n"; # $1:第一个括号匹配到的内容
}

print "$_\n";
if (/(\S+) (\S+), (\S+)/) { # $i:第i个括号匹配到的内容
print "words were $1 $3 $2\n";
}

my $dino = "I fear that I'll be extinct after 10000 years.";
if ($dino =~ /(\d*) years) { #绑定操作符,用右边的匹配左边的字符串或变量
print "That said '$1' years.\n"; #捕捉数字
}

$_ = "Hello there, neighor";
if (/(there)?, (nei|ber)/) { #匹配串是'there, nei'或者是'there, ber',匹配到了第一个
print "The word was $1\n"; #于是输出第一个捕捉串there
print "The word was $2\n"; #输出第二个括号中的部分nei
}

$_ = "Hello there, neighor";
if (/(there)*, (nei|ber)/) { #这里用*也是可以的
print "The word was $1\n";
print "The word was $2\n";
}

if (/(there)?there, (nei|ber)/) { #匹配串是'there, nei'或者是'there, ber',匹配到了第一个
print "The word was $1\n"; #但是匹配到的there是括号外面的there,并不是第一个括号中的there
print "The word was $2\n"; #输出第二个括号中的nei
}

if (/(?:there)?(nei|ber)/) { #匹配串是'there nei'或者是'there ber',匹配到了第一个
print "The word was $1\n"; #但是there使用了不引用修饰符,于是$1指代的就是nei
}

$_ = "Hello there, neighor";
if (/\s(\w+),/) { #匹配规则,先是一个空格,然后是一个单词,然后是一个","
print "The matched word was $&\n"; #在次引用了自动匹配变量$&,指代匹配到的内容
print "The character before matched was $`\n"; #在次引用了自动匹配变量$&,指代匹配到内容之前的字符
print "The character after matched was $'\n"; #在次引用了自动匹配变量$&,指代匹配到内容之后的字符
}

$_ = "Hello there, neighor";
if (/(\w{3,}),/) { #用数字指定匹配3个以上的字符,然后紧跟着还要有个','
print "The matched word was $&\n"; #在此可以看到输出部分比着上面的少了一个空格
}

#Example15 #检验一下模式匹配
#!/usr/bin/perl

while (<>){ #接收键盘输入
chomp; #删除最后的回车
if (/yu/) { #模式匹配字符yu
print "The matched word was |$`<$&>$'|\n"; #提示匹配结果
}
else {
print "No matched: |$_|\n"; #匹配失败,输出 键盘输入的字符
}
}

posted @ 2020-06-21 09:20  smallfishy  阅读(145)  评论(0编辑  收藏  举报