perl Net :: FTP LS与子目录

时间:2012-10-04 22:32:31

标签: perl ftp

LS命令没有给出我在Net :: FTP中的期望。我希望它返回一个字符串数组(文件名),但我得到一个包含字符串数组的数组。

use strict;
use Net::FTP::Common;

my ($host, $user, $pw) = ('<ftp site>', 'user', 'pw');
my $ftp = new Net::FTP($host) || die;
$ftp->login($user, $pw) || die;

my $pwd = $ftp->pwd();
my $subDir = 'subdir/';
my $pattern = '*.txt';
$ftp->cwd($subDir); 

$ftp->pasv(); # passive mode
my @files = $ftp->ls($pattern) || die;

$ftp->cwd($pwd); 

files数组如下所示:

@files [@array [0]] ='filename.txt';

我也尝试过不改变目录,只是做$ftp->ls('subdir/*.txt');同样的结果。

为什么这样做?我误解了回报价值?这是在WINDOWS上。

1 个答案:

答案 0 :(得分:0)

首先,您应该使用

use Net::FTP;

而不是

use Net::FTP::Common;

因为你使用Net :: FTP而不是Net :: FTP :: Common。

现在问题。


文档说:

  

在数组上下文中,返回从服务器返回的行列表。在标量上下文中,返回对列表的引用。

这肯定意味着

  

在列表上下文中,返回服务器返回的行列表。在标量上下文中,返回对这些行数组的引用。

你在标量语境中调用它。你想要

my $files = $ftp->ls($pattern)
   or die;  # || would work, just not idiomatic.

for my $file (@$files) {
   ...
}

你可以在列表上下文中调用ls,然后你就会牺牲错误检查。

# No way to determine whether empty means error or no files.
my @files = $ftp->ls($pattern);

for my $file (@files) {
   ...
}