打印输出到屏幕与输出到文件不同

使用print运算符将键/值数组写入外部 javascript 文件会生成与打印到屏幕不同的输出,尽管我尽了最大努力,但我无法弄清楚原因。具体来说,当打印到屏幕时,正如预期的那样,我的 Perl 脚本输出:

var genusSpecies={"Adam's Needle (Yucca filamentosa)":["Adam's Needle (Yucca filamentosa)1.jpg","._Adam's Needle (Yucca filamentosa)2.jpg"...

然而,当打印到外部 JavaScript 文件时,点下划线._被错误地添加到数组的键和值中,输出:

var genusSpecies={"._Adam's Needle (Yucca filamentosa)":["._Adam's Needle (Yucca filamentosa)1.jpg","._Adam's Needle (Yucca filamentosa)2.jpg"...

这是我的 Perl 脚本:

#!/usr/bin/perl
use strict;
use warnings;

use JSON::PP;

use English;  ## use names rather than symbols for special variables

my $dir = './Plants1024';

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 =~ /.(jpe?g|png)$/i;  ## entry must have jpg, jpeg, or png extension, case insensitive
    my $genus = $file =~ s/d*.(?i)(jpe?g|png)(?-i)$//r;
    push(@{$genus_species{$genus}}, $file);  ## push to array, the @{} is to cast the single entry to a reference to a list

}

@{$genus_species{$_}} = sort @{$genus_species{$_}}
   for keys(%genus_species);

my $str = (JSON::PP->new->utf8->canonical->encode(%genus_species));  ## define array in Javascript outputting elements containing image file names

print "var genusSpecies=", $str;  ## Inserted this line to test "print" output... prints properly WITHOUT adding "._"

my $filename = './Plants1024/PhotoArray.js';

 open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
 print $fh "var genusSpecies=", $str;  ## saves JavaScript key/value array in external JavaScript file, BUT improperly prepends "._" to both keys and values 
 close $fh;

有趣的是,只有在我的 Raspberry Pi4 上执行这个 Perl 脚本时,屏幕和文件的输出才会不同,._在写入的文件中添加数组键/值。

在我的 Mac 上,正如预期的那样,屏幕和文件输出是相同的。更重要的._是,在 Mac 上执行我的 Perl 脚本时没有错误地添加。

也许数组键/值中的空格导致了这种行为,但为什么只在 Raspberry Pi4 而不是 Mac 上?请指教。

回答

默认情况下,ls隐藏以.

$ ls -1
'Adam'''s Needle (Yucca filamentosa)'

$ ls -a1
.
..
'._Adam'''s Needle (Yucca filamentosa)'
'Adam'''s Needle (Yucca filamentosa)'

这导致您认为您没有这样的文件,但它们存在。

readdir不会忽略此类文件。您可以通过添加解决此问题

next if $file =~ /^./;

虽然readdir不会忽略带有前导的文件.,但它可能会忽略._Mac 上带有前导的文件。Mac 创建此类文件以存储有关同名文件的额外信息。我猜您正在阅读的目录是在 Mac 上创建的。


以上是打印输出到屏幕与输出到文件不同的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>