-->
脚本如下:
#!/usr/bin/perl
#evalformat.pl
#与STDOUT文件句柄相关联的动态计算的格式
use warnings;
use strict;
my @values=qw(first second third fourth fifth sixth penultimate utimate);
my $width=0;
foreach (@values){
my $newwidth=length $_;
$width=$newwidth if $newwidth > $width;
}
my $definition = "This is the \@".('<'x($width-1))." line\n".'$_'."\n.\n";
eval "format STDOUT=\n$definition";
write foreach @values;
运行结果:
[root@supersun text]# ./evalformat.pl
This is the first line
This is the second line
This is the third line
This is the fourth line
This is the fifth line
This is the sixth line
This is the penultimate line
This is the utimate line
分析脚本:
- 计算数组中元素的字串长度
- 将格式赋值给变量
- 用eval进行二次计算实现格式的定义
- 打印到标准输出
知识点:
定义一个格式:
format MYFORMAT=
this is a @<<<< justified field
"left"
.
注意格式的定义以 "."结束
将格式到印到与格式一样名称的文件句柄中
write MYFORMAT;
如果想将格式打印到标准输出可以用以下语句
$~='MYFORMAT';
write;
或上面脚本中的定义一个与STDOUT相关联的格式
变量赋值时表达式的使用
$definition = "This is the \@".('<'x($width-1))." line\n".'$_'."\n.\n";

发表评论