我是 Perl 新手,似乎遇到了一些我不理解且出乎意料的行为。
我正在尝试编写一个函数,尝试从数组中存储的可能位置列表加载配置文件。我使用 foreach 循环来迭代数组并检查文件是否存在,但在第一次迭代之后,glob 返回 undef,即使传递给它的值是静态的单引号字符串也是如此。为什么?
这是代码:
package MyPackage;
use warnings; use strict;
our @ConfigSearchPaths = (".", "~");
our $DefaultConfigName = ".my_config_file";
sub load_user_config
{
my ( $obj, $filename ) = @_;
$filename ||= $DefaultConfigName;
CONFIG_SEARCH: foreach my $search_path (@ConfigSearchPaths)
{
$file_path = glob( "$search_path/$filename" );
# I added this line to test if the issue was related to interpolation
# but to my surprise, this also returns 'undef' after the first iteration.
$file_path_2 = glob( '~/.my_config_file');
if( -r $file_path )
{
# Parse the file...
}
}
}
答案就在文档中:请参阅glob。
在标量上下文中,
迭代此类文件名扩展,当列表耗尽时返回 undef。glob
在标量上下文中,
glob
充当迭代器。在第一次迭代中, glob
返回文件本身,在第二次迭代中,它返回 undef
,因为没有更多匹配项。
如果不想迭代,请使用列表上下文:
my @file_paths = glob "$search_path/$filename";
我建议使用 Path::Tiny 或类似的模块来为您处理路径。