热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[OReilly_Learning_Perl_5th_Edition]_Chap06_Exercises

3.[15]Writeaprogramtolistallofthekeysandvaluesin%ENV.PrinttheresultsintwocolumnsinASCIIbet





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");
}
}

}



推荐阅读
author-avatar
qzq9037091
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有