一个被动态计算的格式的举例

| 暂无评论 | 暂无引用通告

-->

脚本如下: 

#!/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";

eval的使用

格式中变量的使用

暂无引用通告

发送引用通告网址: http://supersun.info/mt/mt-tb.cgi/620
如果您想引用这篇日记到您的Blog,请复制上面的链接,放置到您发表文章时的相应界面中。

发表评论

最新资源

  • IMG_1437.JPG
  • line.png
  • bar.png
  • perl_calander.jpg

关于此日记

此日记由 supersun 发表于 2007年4月25日 14:49

此Blog上的上一篇日记红烧肉的做法

此Blog上的下一篇日记perl中的"格式"的使用

首页归档页可以看到最新的日记和所有日记。