gpt4 book ai didi

perl - perl的if条件下匹配文件名

转载 作者:行者123 更新时间:2023-12-02 21:39:11 25 4
gpt4 key购买 nike

我的文件名为 lin.txt 和 lin1.txt 以及其他 .txt 文件。我只需要找到这些文件并仅按一个打印其内容。我有下面的代码,但它与以 lin* 开头的文件不匹配。这是什么问题?

$te_dir= "/projects/xxx/";
opendir (DIR, $te_dir) or die $!;
while (my $file = readdir(DIR))
{
if ($file=~/\.txt/)
{
#// Doing some tasks.

if($file ~= 'lin*.txt')
{
$linfile=$te_dir/$file;
open(LINFILE, $linfile) or die "Couldn't open file $file:$!";
while(my $line = <LINFILE>)
{
print $line;
}
close LINFILE;

}

}

}

最佳答案

您正在将 glob(shell 通配符)与正则表达式混合在一起。这是两种不同的形式主义,具有不同的语法和语义。在正则表达式(Perl 匹配使用的内容)中,n* 匹配零次或多次出现的字符 n。你可能是说

if ($file =~ /lin.*\.txt/)

另请注意运算符中的语法错误。第一个条件中的 =~ 是正确的,但在进行比较时将其错误拼写为 ~= 。 (也许这只是一个转录错误;对我来说,这会产生一个明显的语法错误,因此脚本首先不会运行。)

正如 @brianadams 的回答中所述,正确的正则表达式是

if ($file =~ /^lin.*\.txt$/)

使用行首 ^ 和行尾 $ anchor 来防止例如来自匹配的feline.txt.html。 Perl 正则表达式的默认行为是在输入字符串中的任意位置查找匹配项。

关于perl - perl的if条件下匹配文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20739955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com