我正在尝试读取文件,然后想要在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
?
答案 0 :(得分:1)
累积变量中的输出并在循环结束后打印?
my $data;
while(<$booklist>){
($perlbook, $javabook, $cbook) = split (',');
$bookHash{$cbook} = $cbook;
$data = $bookHash{$cbook} ;
$output .= $data;
}
print $output;
答案 1 :(得分: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