0

我正在尝试读取文件,然后想在while循环外打印输出。有没有办法做到这一点?

这就是我正在做的事情:

   my $booklistFile= file.txt;
   my $perlbook;
   my $javabook;
   my $cbook;
   my $data;

   open my $booklist, "<", $booklistFile or die "can not open the file";
   my %bookHash = ();

   while(<$booklist>)
   {
     ($perlbook, $javabook, $cbook) = split (',');
     $bookHash{$cbook} = $cbook;
     $data = $bookHash{$cbook} ;

     print $data;
   }

这将打印循环$data内部。while有没有办法可以在循环$data外打印?while

4

2 回答 2

1

Accumulate the output in a variable and print after the loop ends?

my $data;
while(<$booklist>){
    ($perlbook, $javabook, $cbook) = split (',');
    $bookHash{$cbook} = $cbook;
    $data = $bookHash{$cbook} ;
    $output .= $data;
}
print $output;
于 2012-07-10T14:26:18.073 回答
1

我只是猜测你在这里尝试做什么。如果我查看您的代码,您可能有一个包含书名的逗号分隔记录的文件?

如果是这样,下面的代码段将打印所有 C 书籍,根据您的说法,这些书籍应该在您输入行的第三个字段中 ($perlbook, $javabook, $cbook) = split (',');

...
my $booklistFile= 'file.txt';
open my $bookhandle, '<', $booklistFile or die "can not open $!";
my %bookHash = ();

while(my $line = <$bookhandle>) {
   chomp $line;
   my @record = split /\s*,\s*/, $line;
   push @{ $bookHash{PERL} }, $record[0];
   push @{ $bookHash{JAVA} }, $record[1];
   push @{ $bookHash{C}    }, $record[2];
}

# print all c books alphabetically sorted
print join "\n", sort @{ $bookHash{C} };
...

现在,您可以在循环之后按排序顺序获取 C 书籍。

循环部分也可以通过使用散列片不重复地编写:

   ...
   ...
   my @record = split /\s*,\s*/, $line;
   for my $category ( @bookHash{'PERL', 'JAVA', 'C'} ) {
      push @$category, shift @record
   }
   ...
   ...

问候,

rbo

于 2012-07-10T14:47:08.353 回答