52、使用Perl语言,利用智能匹配运算符,判断用户输入的一个模式是否能匹配给定数组 @array = qw(Fred Wilma Barney Betty Larry Pebbles Bamm - Bamm) 中的至少一个元素
以下是实现该功能的Perl代码:
#!/usr/bin/perl
use 5.10.1;
my @array = qw(Fred Wilma Barney Betty Larry Pebbles Bamm-Bamm);
print "The elements are (", join(" ", @array), ")\nEnter a pattern:\n";
chomp(my $pattern = <STDIN>);
if ($pattern ~~ @array) {
print "At least one element matches\n";
} else {
print "No element matches\n";
}
上述代码会提示用户输入一个模式,然后使用智能匹配运算符 ~~ 判断该模式是否能匹配数组中的至少一个元素,并输出相应的结果。
53、使用Perl语言,设置环境变量 TZ 为太平洋时区(不同系统可能不同,如 PST8PDT 或 US/Pacific),然后执行 date 命令
在不同系统下的实现代码如下:
在部分系统使用 PST8PDT 时:
#!/usr/bin/perl
use strict;
use warnings;
$ENV{TZ} = 'PST8PDT';
exec 'date';
在 Mac OS X 系统使用 US/Pacific 时:
#!/usr/bin/perl
use strict;
use warnings;
$ENV{TZ} = 'US/Pacific';
exec 'date';
54、编写一个程序,设置环境变量 TZ 然后执行 date 命令。
在不同系统上的示例代码如下:
在部分系统上使用 'PST8PDT' 作为 TZ 值:
#!/usr/bin/perl
use strict;
use warnings;
$ENV{TZ} = 'PST8PDT';
exec 'date';
在 Mac OS X 系统上使用 'US/Pacific' 作为 TZ 值:
#!/usr/bin/perl
use strict;
use warnings;
$ENV{TZ} = 'US/Pacific';
exec 'date';
55、编写一个程序,打印所有环境变量。然后将其转换为 CGI 程序。
打印所有环境变量的程序:
```perl
#!/usr/bin/perl
foreach my $key ( sort keys %ENV ) {
printf "%-30s %s\n", $key, $ENV{$key};
}
转换为 CGI 程序:
#!/usr/bin/perl
print "Content-type: text/plain\n\n";
foreach my $key ( sort keys %ENV ) {
printf "%-30s %s\n", $key, $ENV{$key};
}
##56、使用带管道的 open 函数而非反引号编写一个程序,实现统计当前目录下文件列表中每个用户和每个用户组出现的次数。
该程序使用 `open` 函数,将命令作为文件名,并在文件名后加上管道`"|"。由于管道在命令之后,就可以从这个文件句柄中读取内容。在 `while` 循环中使用该文件句柄逐行读取。程序如下:
```perl
#!/usr/bin/perl
use strict;
use warnings;
open my $ls, '-|', 'ls', '-l'; # 三参数及以上形式
my( %users, %groups );
while( <$ls> ) {
next if /^total/;
my( $perm, $n, $user, $group ) = split;
$users{$user}++;
$groups{$group}++;
}
foreach my $user ( sort keys %users ) {
print

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



