我有以下代码:
use strict;
use warnings;
use Net::FTP;
my $counter;
my $ftp = Net::FTP->new( "ftp.metagenomics.anl.gov", Debug => 0 )
or die "Cannot connect.\n";
$ftp->login() or die "Login problems.\n";
$ftp->cwd("/projects") or die "Cannot change directory.\n";
for my $directory ( $ftp->ls ) {
$ftp->cwd($directory);
my ( $remote_file_content, $remote_file_handle );
open( $remote_file_handle, ">", \$remote_file_content );
$ftp->get( "metadata.project-" . $directory . ".json", $remote_file_handle )
or die "Get failed.\n";
while ( my $line = $remote_file_content ) {
$counter++;
if ( $line =~ /"biome":{"unit":"","required":"1","value":"([A-Za-z0-9_\-. ]*)",/ ) {
print $counter. "\t" . $directory . "\t" . $1 . "\n";
}
}
close $remote_file_content;
$ftp->cwd("..");
}
然而,第一个文件被反复阅读......它就像一个无限循环,我不知道为什么它永远不会读完同一个文件。你有什么想法吗?
答案 0 :(得分:1)
while (my $line = $remote_file_content) {
$counter++;
if ($line =~ /"biome":{"unit":"","required":"1","value":"([A-Za-z0-9_\-. ]*)",/) {
print $counter."\t".$directory."\t".$1."\n";
}
}
此循环仅在$remote_file_content
为假(即为空)时结束,因为您没有last
或其他方式退出循环。
但是,您永远不会在此循环中更改$remote_file_content
。
这意味着,一旦你输入它,你将永远不会离开循环。
答案 1 :(得分:0)
您是尝试单独还是整体处理文件中的每一行?
如果你是整体做的,摆脱while循环并执行此操作:
for my $directory ( $ftp->ls ) {
$ftp->cwd($directory);
my ( $remote_file_content, $remote_file_handle );
open( $remote_file_handle, ">", \$remote_file_content );
$ftp->get( "metadata.project-" . $directory . ".json", $remote_file_handle )
or die "Get failed.\n";
$counter++;
if ( $remote_file_content =~ /"biome":{"unit":"","required":"1","value":"([A-Za-z0-9_\-. ]*)",/ ) {
print $counter. "\t" . $directory . "\t" . $1 . "\n";
}
close $remote_file_handle;
$ftp->cwd("..");
}
如果您想分别处理每一行:
for my $directory ( $ftp->ls ) {
$ftp->cwd($directory);
my ( $remote_file_content, $remote_file_handle );
open( $remote_file_handle, ">", \$remote_file_content );
$ftp->get( "metadata.project-" . $directory . ".json", $remote_file_handle )
or die "Get failed.\n";
foreach my $line (split "\n", $remote_file_content ) {
$counter++;
if ( $line =~ /"biome":{"unit":"","required":"1","value":"([A-Za-z0-9_\-. ]*)",/ ) {
print $counter. "\t" . $directory . "\t" . $1 . "\n";
}
}
close $remote_file_handle;
$ftp->cwd("..");
}
您正在关闭文件名而不是文件句柄,关闭失败,您只是不知道它,因为当变量超出范围时会自动调用close。