【问题标题】:Removing file extension from an array variable从数组变量中删除文件扩展名
【发布时间】:2021-01-26 04:24:25
【问题描述】:

我正在尝试删除出现在输出数组的许多(但不是全部)变量中的 .png 文件扩展名。显示扩展名的数组变量这样做是因为它们不是从“Genus_species#.png”格式的文件名生成的,其中“#”是一个数字。相反,它们是从“Genus_species.png”格式的未编号文件名生成的。我相信这行代码造成了这个问题:“$genus = $file =~ s/\d.png$//r;”。我该如何解决这个问题?请指教。

这是我的 Perl 脚本:

#!/usr/bin/perl
use strict;
use warnings;
use English;   ## use names rather than symbols for special varables

my $dir = '/Users/jdm/Desktop/xampp/htdocs/cnc/images/plants';

opendir my $dfh, $dir  or die "Can't open $dir: $OS_ERROR";
my %genus_species;  ## store matching entries in a hash

for my $file (readdir $dfh)
{
    next unless $file =~ /.png$/; ## entry must have .png extension
    my $genus = $file =~ s/\d\.png$//r;
    push(@{$genus_species{$genus}}, $file); ## push to array,the @{} is to cast the single entry to a referance to an list
}

for my $genus (keys %genus_species)
{
    print "$genus = ";
    print "$_, " for sort @{$genus_species{$genus}}; # sort and loop     though entries in list referance
    print "\n";
}

这是输出的数组:

Euonymus_fortunei = Euonymus_fortunei1.png, Euonymus_fortunei2.png, Euonymus_fortunei3.png, 
Polygonum_persicaria = Polygonum_persicaria1.png, Polygonum_persicaria2.png, 
Polygonum_cuspidatum.png = Polygonum_cuspidatum.png,

请注意,变量“Polygonum_cuspidatum.png”无意中包含了文件扩展名,因为该变量是从名称中缺少数字的文件生成的。具体来说,这个变量应该是:

Polygonum_cuspidatum = Polygonum_cuspidatum.png

再次,请告知如何解决此问题。谢谢。

【问题讨论】:

    标签: arrays perl variables


    【解决方案1】:

    如果文件名中有多位数字,您将看到同样的问题。这都是因为选择了正则表达式:

     s/\d\.png$//r
    

    这会查找一个数字,后跟.png。如果您不想要数字,或者 .png 之前的任意数字,请修改您的正则表达式:

    s/\d*\.png$//r
    

    表示“零个或多个数字后跟 .png 在字符串的末尾”。

    【讨论】:

    • 我在使用“s/\d*\.png$//r”时遇到了错误。我正在研究原因。
    • 添加后;在表达式的末尾,它可以工作......但它只返回 513 个条目而不是预期的 585 个。我正在研究为什么。
    • 没有超过数字 9 的文件名。真是奇怪,增加搜索范围会返回更少的文件!
    • Re "这表示“零个或多个数字后跟 .png 在字符串的末尾”。",不,它没有。那将是\d*\.png\z。你所拥有的是“零个或多个数字后跟.png,可能还有字符串末尾的LF。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2023-03-10
    • 2011-10-07
    • 2013-03-14
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    相关资源
    最近更新 更多