This is perl 5, version 30, subversion 1 (v5.30.1) built for MSWin32-x64-multi-thread
Win10
cygwin我不知道如何使用opendir。下面是我的示例代码:
sub test($) {
my $dir = shift;
opendir (DIR, $dir) || die "Couldn't open dir $dir $!";
}
sub main() {
my $dir = `pwd`;
test($dir);
}错误消息
Couldn't open dir /home/skidmarks/Projects/Perl
Invalid argument at ./test.py line .pwd返回unix格式的目录路径('/')。我尝试过使用windows格式的目录路径('\')。唯一有效的方法是对路径使用文字字符串,例如,“。或者"some_directory_path“。
我不能使用opendir中的变量作为路径吗?
发布于 2020-01-07 06:18:41
发布于 2020-01-07 07:38:00
尝试下面这段代码,它可以很好地与Strawberry perl配合使用。
还要尝试将完整路径放在双引号"c:\Program Files\Common Files"中。
如果未提供目录名,则脚本将列出当前的目录
用法:perl script.pl "C:\Users\User_name"
use strict;
use warnings;
use feature 'say';
my $dir_name = shift || '.';
opendir(my $dir, $dir_name)
or die "Couldn't open $dir_name";
map{ say } readdir($dir);
closedir $dir;注意:在Cygwin终端中导航到目标目录,然后发出命令pwd。在Cygwin中运行的Perl脚本可能会得到以下形式的路径。
发布于 2020-01-07 13:29:25
安装了最新版本的Cygwin,并使用稍微修改过的代码进行了测试--工作正常。
注:pwd是Linux/UNIX命令,它在MS Windows中产生错误,但在模拟Linux/UNIX环境的Cygwin中工作(二进制不兼容,需要重新编译程序)
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
sub test($) {
my $dir = shift;
opendir(my $dh, $dir)
or die "Couldn't open dir $dir $!";
map{ say } readdir($dh);
close $dh;
}
sub main() {
my $dir = `pwd`;
chomp $dir;
print "[$dir]\n";
test($dir);
}
main();函数main在perl中不是必需的(main()函数是C/C++入口点),通常代码如下
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
my $dir = `pwd`; # pwd is UNIX/Linux command will give an error in MS Windows
chomp $dir; # trim \n at the end of $dir
say "DIRECTORY: [$dir]"; # Let's check what we got
test($dir);
sub test {
my $dir = shift;
opendir(my $dh, $dir)
or die "Couldn't open dir $dir $!";
map{ say } readdir($dh);
close $dh;
}https://stackoverflow.com/questions/59619670
复制相似问题