[OReilly_Learning_Perl_5th_Edition]_Chap06_Exercises

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

转载于:https://www.cnblogs.com/cppfans/articles/1692560.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值