perl语言入门级练习记录6&7章 哈希Hash 正则表达式

6.5 练习

  1. [7]写一个程序,提示用户输入given name(名),并给出其对应的family name(姓)。
#!/usr/bin/perl –w
use strict;

my %name = (
	"fred" => "flintstone",
	"dino" => "und",
	"barney"=> "rubble",
	"betty"=> "rubble",
	"jingyi"=>"wang",
	"yq"=>"lee",
	"notsweet"=>"tang"
);
print "Input the first name:";
chomp(my $first=<STDIN>);
(exists $name{$first}) and 
	print "The matched last name is:$name{$first}";

1;
  1. [15]写一个程序,读入一串单词(一个单词一行),输出每一个单词出现的次数。(提示:如果某个作为数字使用值是undefined 的,会自动将它转换为0。)如果输入单词为fred, barney, dino, wilma, fred(在不同行中),则输出的fred 将为3。作为额外的练习,可以将输出的单词按照ASCII 排序。
    (总觉得这道题目的翻译怪怪的)
#!/usr/bin/perl –w
use strict;

print "Input the words\n";
my %words;
while(<STDIN>){
	chomp;
	$words{$_}++;
}
foreach (sort keys %words){
	print "$_ appeared $words{$_} times\n";
}
1;

7.4练习—正则表达式

  1. [10]写一个程序,输出所有提到fred 的行(不要输出其它行)。如果输入字符串Fred, fredrick, Alfred,能匹配上吗?准备一个小的文本文件,其中包含如:“fred lintsotne”以及类似的信息。使用这个文本文件作为此程序的输入,以及本节下面练习的输入。
#!/usr/bin/perl –w
use strict;

open(FILE,$ARGV[0]) or die "Can't open : $!\n";
my @lines = <FILE>;

foreach (@lines){
	/fred/ and print "Match!$_\n";
}
close(FILE);
1;
  1. [6]修改上面的程序,允许匹配Fred。现在它能匹配,Fred, fredrick, Alfred 吗?(将这些名字加入输入文件中)
foreach (@lines){
	/fred|Fred/ and print "Match!$_\n";
}

把上面代码的foreach循环改成这个亚子↑
就可以匹配到fred/Fred。

  1. [6]写一个程序,输出出现句号(.)的行,忽略其它行。使用前面练习中的文件进行练习:它能找到Mr. Slate 吗?
foreach (@lines){
	/\./ and print "Match!$_\n";
}

可以找到Mr. Slate。若只希望找到行末尾的. 使用代码:

foreach (@lines){
	/\.$/ and print "Match!$_\n";
}
  1. [8]写一个程序,输出有一个字母大写,而非所有字母都大写的行。它能匹配Fred,而不匹配fred 和FRED 吗?
foreach (@lines){
	/[A-Z]/g and /[a-z]/g and print "Match!$_\n";
}
能匹配Fred,而不匹配fred和FRED。
  1. [8]额外的练习:写一个程序,它能输出所有同时提到wilma 和fred 的行。
foreach (@lines){
	/wilma/g and /fred/g and print "Match!$_\n";
}
上一篇:将VBS翻译为JS的几种方法


下一篇:Linux - CentOS6.5服务器搭建与初始化配置详解(下)