在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
3. [15] Write a program to list all of the keys and values in %ENV. Print the results in two columns in ASCIIbetical order. For extra credit, arrange the output to vertically align both columns. The length function can help you figure out how wide to make the first column. Once you get the program running, try setting some new environment variables and ensuring that they show up in your output. #!perl use warnings; use strict; use 5.010; use POSIX; #while ((my $key, my $value) = each %ENV) #{ # print "$key => $value"; #} #环境变量名数组 my @envNames = keys %ENV; #最长的环境变量名的长度 my $maxEnvNameLen = length $envNames[0]; shift @envNames; #环境变量名 my $envName = undef; foreach $envName (@envNames) { if (length $envName > $maxEnvNameLen) { $maxEnvNameLen = length $envName; } } #命令行宽度 my $cmdLineWidth = 80; #"NAME"标题 my $envNameTitle = "NAME"; my $envNameTitleFormated = (" " x (POSIX::floor($maxEnvNameLen / 2) - POSIX::floor(length($envNameTitle) / 2))). $envNameTitle; #关联符号,如NAME => VALUE my $associationSymbol = " => "; #"VALUE"标题 my $envValueTitle = "VALUE"; my $envValueTitleFormated = (" " x ($maxEnvNameLen + length($associationSymbol) - (POSIX::floor($maxEnvNameLen / 2) - POSIX::floor(length($envNameTitle) / 2) + length($envNameTitle)) + POSIX::floor(($cmdLineWidth - $maxEnvNameLen - length($associationSymbol)) / 2) - POSIX::floor(length($envValueTitle)/2))).$envValueTitle; #输出标尺 say "1234567890" x (POSIX::ceil($cmdLineWidth / 10)); #输出标题 say $envNameTitleFormated.$envValueTitleFormated; #环境变量值最大允许宽度 my $envValueWidth = $cmdLineWidth - $maxEnvNameLen - length($associationSymbol); for $envName (sort keys %ENV) { printf "%".$maxEnvNameLen."s".$associationSymbol, $envName; #环境变量值 my $envValue = $ENV{$envName}; #环境变量值长度 my $envValueLen = length $envValue; #环境变量值占用的行数 my $envValueLines = POSIX::ceil($envValueLen / $envValueWidth); for (my $i = 0; $i < $envValueLines; ++$i) { chomp(my $tmp = substr($envValue, $i * $envValueWidth, $envValueWidth)); if ($i == 0) { print $tmp."\n"; } else { print((" " x ($maxEnvNameLen + 4)).$tmp."\n"); } } } |
请发表评论