intermediate perl 第8章 练习2 求解

intermediate perl 第8章 练习2 求解

最近在学习 intermediate perl,第八章练习二有些疑问,请高手指点一二,谢谢。问题是

The Professor has to read a logfile that looks like:

Gilligan: 1 coconut
Skipper: 3 coconuts
Gilligan: 1 banana
Ginger: 2 papayas
Professor: 3 coconuts
MaryAnn: 2 papayas
...



He wants to write a series of files, called gilligan.info, maryann.info, and so on. Each file should contain all the lines that begin with that name. (Names are always delimited by the trailing colon.) At the end, gilligan.info should start with:

Gilligan: 1 coconut
Gilligan: 1 banana



Now the logfile is large, and the coconut-powered computer is not very fast, so he wants to process the input file in one pass and write all output files in parallel. How does he do it?

Hint: use a hash, keyed by the castaway name, holding IO::File objects for each output file. Create them as necessary

书中参考答案是

use IO::File;
my %output_handles;
while (<>) {
  unless (/^(\S+):/) {
    warn "ignoring the line with missing name: $_";
    next;
  }
  my $name = lc $1;
  my $handle = $output_handles{$name} ||=
    IO::File->open(">$name.info") || die "Cannot create $name.info: $!";
  print $handle $_;
}

运行之后返回错误
Can't use string ("IO::File") as a symbol ref while "strict refs" in use at /usr/local/lib/perl5/5.8.8/i686-linux/IO/File.pm line 188, <> line 1.

于是改为


use IO::File;
$fh=new IO::File;
my %output_handles;
while (<>) {
  unless (/^(\S+):/) {
    warn "ignoring the line with missing name: $_";
    next;
  }
  my $name = lc $1;
  my $handle = $output_handles{$name} ||=
    $fh->open(">$name.info") || die "Cannot create $name.info: $!";
  print $handle $_;
}

能够运行,也能按行首:前字段分成若干文件,可是文件都是空的,请问如何修改,再次感谢
加上

[Copy to clipboard] [ - ]
CODE:
use strict;
use warnings;

你就会发现问题的所在,你看出下面的代码问题在什么地方?

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;
use warnings;
use IO::File;
my $fh =new IO::File;
my $a = $fh->open(">a");
my $b = $fh->open(">b");
print $a "To file a\n";
print $b "To file b\n";

这和你代码是同一类型的
如果看不出就运行一下,结果和你的是类似的
但是会给你个提示
注意$fh->open的返回值,并不是你想象的那样,返回一个文件句柄,而是返回1(成功)
解决方法很简单


[Copy to clipboard] [ - ]
CODE:
IO::File->new

就可以了
下面的代码就是可以的

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
use strict;
use warnings;
use IO::File;
my $file = "justatest";
my $fh =IO::File->new(">$file");
print $fh "To file just a test\n"

感谢 churchmice 细致的讲解。