- 论坛徽章:
- 0
|
Mastering Perl 上的一个例子
- #!/usr/bin/perl
- use Devel::Size qw(size);
- my $n;
- print_message( "Before I do anything" );
- print "Size is ", size( \$n );
- print_message( "After I assign a string" );
- $n = '1';
- print "Size is ", size( \$n );
- print_message( "After I use it as a number" );
- my $m = $n + 1;
- print "Size is ", size( \$n );
- sub print_message { print "\n", "-" x 50, "\n$_[0]\n", "-" x 50, "\n" }
复制代码 输出:
--------------------------------------------------
Before I do anything
--------------------------------------------------
Size is 24
--------------------------------------------------
After I assign a string
--------------------------------------------------
Size is 56
--------------------------------------------------
After I use it as a number
--------------------------------------------------
Size is 64
因为好几个地方都用到print_message,每次复制粘贴比较麻烦,就把它作成一个小的模块
- #Print.pm
- package Print;
- require Exporter;
- our @ISA = qw(Exporter);
- our @EXPORT = qw(print_message);
- our @EXPORT_OK = qw();
- our $VERSION = 1.00;
- sub print_message {
- print STDERR "\n", "-" x 50,
- "\n$_[0]\n", "-" x 50, "\n";
- }
- 1
- #size.plx
- #!/usr/bin/perl
- use strict;
- use warnings;
- use Devel::Size qw/size/;
- use Print;
- my $n;
- print_message("Before I do anything");
- print "Size is ", size(\$n);
- print_message("After I do something");
- $n = '1';
- print "Size is ", size(\$n);
- print_message("After I do anything");
- my $m = $n + 1;
- print "Size is ", size(\$n);
复制代码 输出变成这样了:
--------------------------------------------------
Before I do anything
--------------------------------------------------
--------------------------------------------------
After I do something
--------------------------------------------------
--------------------------------------------------
After I do anything
--------------------------------------------------
Size is 24Size is 56Size is 64
我的解决方法有两个:
1. 在size.plx 文件开始设置 local $| = 1;
2. 在- print "Size is ", size(\$n);
复制代码 后面添加换行符
即- print "Size is ", size(\$n), "\n";
复制代码 但对第二个文件的错误输出还是不太理解,请那位大侠解释下,谢谢了  |
|