10.10 练习
- [25]写一个程序,能重复要求用户猜测某个在1 到100 之间的数字,直到猜对为止。你的程序应当能随机的产生一个
数字,使用公式int(1 + rand 100)◆。当用户猜测错误时,程序应该回应“Too high”或者“Too low”。如果用户输入quit
或exit,或者回车时,程序应立即退出。如果用户猜测正确,程序也退出。
#! /usr/bin/perl –w
use strict;
my $num=int(1 + rand 100);
print "Guess the random number:";
while(<>){
$_>$num and print "Too high!\n";
$_<$num and print "Too low!\n";
$_==$num and print "Bingo!\n" and last
};
1;
11.6 练习
- [15]写一个程序,读入命令行中的一串文件,报告其是否可读,可写,可执行,或不存在。(提示:如果一个函数能一次对一个文件进行所有的检测将非常有帮助。)如果一个文件被执行chmod 0 操作,将报告什么?(在Unix 系统中,chmod 0 some_file 将一个文件变成不可读,不可写,不可执行的)在大多数shell 中,星号(*)表示当前目录中的所有的普通文件。也就是说,可以输入像./ex11-1 *这样的命令,返回当前目录下文件的属性。
#! /usr/bin/perl –w
use strict;
sub ftest{
my $file=$_;
my $state;
-r $file and $state.="r";
-w $file and $state.="w";
-x $file and $state.="x";
-e $file and $state.="e";
$state
};
print "$_:".&ftest($_)."\n" foreach @ARGV;
1;
- [10]写一个程序,找出命令行中存在时间最长的文件名,并报告其天数。当参数为空时,其行为如何(例如,命令行中没有输入任何的文件)?
#! /usr/bin/perl –w
use strict;
@ARGV or die "ERROR!\n" ;
my $oldf = pop @ARGV;
my $oldtime = -M $oldf;
-M $_ > $oldtime and ($oldf,$oldtime)=($_,-M $_) foreach @ARGV;
print "$oldf,$oldtime\n";
1;
13.5 练习
- [10]写一个程序,读入一串数字,将它们按照数字排序,将结果按右对齐的列打印出来。使用下面的数据进行检测:
17 000 04 1.50 3.14159 -10 1.5 4 2001 90210 666
#! /usr/bin/perl –w
use strict;
print "input some numbers:\n";
#my @num=<>;
my @num=(17,000,04,1.50,3.14159,-10,1.5,4,2001,90210,666);
@num=sort @num;
print "@num";
1;
- [15]写一个程序,将下例hash 数据根据姓(last name)按照大小写无关的字母顺序进行排序,并把结果打印出来。当last name 相同时,再按照名(first name)排序(不用关心大小写)。因此,第一个输出的的名字是Fred’s,最后一个是Betty’s。具有相同family name 名字在一起。不要改变数据。输出名字的大小写应当和这里的一样。
my %last_name = qw{
fred flintstone Wilma Flintstone Barney Rubble
betty rubble Bamm-Bamm Rubble PEBBLES FLINTSONE
};
#! /usr/bin/perl –w
use strict;
my %last_name = qw{
fred flintstone Wilma Flintstone Barney Rubble
betty rubble Bamm-Bamm Rubble PEBBLES FLINTSONE
};
my @name = sort{
"\u$last_name{$a}" cmp "\u$last_name{$b}"
or "\u$a" cmp "\u$b"
}keys %last_name;
print "$last_name{$_} $_\n" foreach @name;
1;
- [15]写一个程序,查找给定子串在给定字符串中出现的每一个位置,输出子串出现的位置。例如,给定字符串为“This isa test.”给定子串为“is”,它应当输出2 和5。如果子串是“a”,它应当输出8。如果子串为“t”呢?
#! /usr/bin/perl –w
use strict;
my $str = "This isa test.";
my $pos = -2;
my $char = 'a';
while ($pos+1){
$pos=index($str,$char,$pos+1);
$pos>=0 and print "$pos\n"
};
1;