4.11 练习
- [12]写一个名为&total 的子程序,返回一列数字的和。提示:子程序不应当有任何的I/O 操作;它处理调用的参数,返
回处理后的值给调用者。结合下面的程序来练习,它检测此子程序是否正常工作。第一组数组之和我25。
my @fred = qw{ 1 3 5 7 9 };
my $fred_total = &total(@fred);
print “The total of @fred is $fred_total.\n”;
print "Enter some numbers on separate lines: ";
my $user_total = &total();
print “The total of those numbers is $user_total.\n”;
#!/usr/bin/perl –w
use strict;
my @fred = qw{ 1 3 5 7 9 };
my $fred_total = &total(@fred);
print "The total of \@fred is $fred_total.\n";
print "Enter some numbers on separate lines: ";
my $user_total = &total(<STDIN>);
print "The total of those numbers is $user_total.\n";
sub total{
my $sum;
$sum+=$_ foreach @_;
$sum;
}
1;
- [5]利用上题的子程序,写一个程序计算从1 到1000 的数字的和.
#!/usr/bin/perl –w
use strict;
my @num =1..1000;
my $total = &total(@num);
print "The total of 1 to 1000 is $total.\n";
sub total{
my $sum;
$sum+=$_ foreach @_;
$sum;
}
1;
- [18]额外的练习:写一个子程序,名为&above_average,将一列数字作为其参数,返回所有大于平均值的数字(提示:
另外写一个子程序来计算平均值,总和除以数字的个数)。利用下面的程序进行测试:
my @fred = &above_average(1…10);
print “@fred is @fred\n”;
print “(Should be 6 7 8 9 10)\n”;
my @barney = &above_average(100, 1…10);
print “@barney is @barney\n”;
print “(Should be just 100)\n”;
#!/usr/bin/perl –w
use strict;
my @fred = &above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";
my @barney = &above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";
sub average{
my $ave;
$ave+=$_ foreach @_;
$ave/=@_;
$ave;
}
sub above_average{
my $ave=&average(@_);
my @above;
$_>$ave and push(@above,$_) foreach @_;
@above;
}
1;
5.11 练习
- [7] 写一个程序,类似于cat,但保持输出的顺序关系。(某些系统的名字可能是tac。)如果运行此程序:./tac fred barney betty, 输出将是文件betty 的内容,从最后一行到第一行,然后是barney, 最后是fred, 同样是从最后一行到第一行。(注意使用./确保调用的是你自己的程序,而非系统提供的)
#!/usr/bin/perl –w
use strict;
foreach (reverse <STDIN>) {
open(FILE, "$_") || die "Can't open : $!\n";
my @lines = <FILE>;
print reverse(@lines),"\n";
}
1;
- [8]写一个程序,要求用户在不同的行中输入一些字符串,将此字符串打印出来,规则是:每一条占20 个字符宽度,右
对齐。为了确保正确的输出,在开头打印出一串数字作为比较(帮助调试)。注意,不要犯19 个字符宽度的错误。例如,
如果输入,hello, good-bye,则输出为:
123456789012345678901234567890123456789012345678901234567890
hello
good-bye
#!/usr/bin/perl –w
use strict;
my @items = <>;
print ((1..9,0)x6);
printf "\nThe items are:\n". ("%20s"x @items), @items;
1;
- [8]修改上一个程序,允许用户选择宽度,如,用户输入30,hello, good-bye(在不同的行中),则每一行的宽度为30。(提示:参阅第二章相应部分)。提示,如果选择的宽度太长,可以增加比较行的长度。
#!/usr/bin/perl –w
use strict;
my @items = <>;
print "Please input ideal width:";
my $wid = <>;
print ((1..9,0)x6);
printf "\nThe items are:\n";
printf "%*s",$wid,$_ foreach @items;
1;
增加比较行的长度这句话有点没看懂。