这几乎可以满足您的需求。
假设您的产品代码存储在一个名为 products.csv 的文件中,如果您将下面的代码保存在一个名为“go”的文件中,那么执行
chmod +x go
./go < products.csv
它可能需要一点点调整......
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Cwd;
my $Debug=1; # Set to 0 to turn off debug output
my $photosdir="/tmp"; # Or wherever your photos are
# Go to photos directory and load names of all JPEGs into array @photos
chdir $photosdir or die "Unable to chdir() to $photosdir\n";
my @photos=<*.jpg>;
# Debug - output photo filenames
print Dumper @photos if $Debug;
# Read product codes from our stdin
while(<>){
chomp;
my $product = $_ ;
$product =~ s/;.*//;
print "Finding photo for product: $product\n" if $Debug;
# Run through all photo filenames and find longest match
my $longestmatch=0;
my $bestimage="<NONE>";
foreach my $photo (@photos){
# Strip extension off photo name
$photo =~ s/\.jpg//;
print "Assessing photo $photo\n" if $Debug;
if($product =~ m/(^$photo)/ ){
my $matchlength = length($&);
if($matchlength > $longestmatch){
print "Best match so far: $photo, ($matchlength characters)\n" if $Debug;
$longestmatch = $matchlength;
$bestimage = $photo . ".jpg";
}
}
}
print "$product,$bestimage\n";
}
实际上,您可以使用散列更优雅、更快地完成它。与其查看数千张照片中的每一张,直到找到最长的匹配项,不如尝试查看产品的前 n 个字母是否在哈希中,如果不是,则尝试前 n-1 个字母,然后尝试前 n-2 个字母, 像这样。对于大量产品和照片,它应该运行得更快。
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Cwd;
my $Debug=1; # Set to 0 to turn off debug output
my $photosdir="/tmp"; # Or wherever your photos are
# Go to photos directory and load names of all JPEGs into array @filenames
chdir $photosdir or die "Unable to chdir() to $photosdir\n";
my @filenames=<*.jpg>;
# Now create hash of photonames without ".jpg" extension
my %photos;
for my $photo (@filenames){
$photo =~ s/\.jpg//;
# So if there was a file "xyz.jpg", $photos{"xyz"} will be defined
$photos{$photo}=1;
}
# Debug - output photo filenames
print Dumper \%photos if $Debug;
# Read product codes from our stdin
while(<>){
chomp; # remove end of line
my ($product,$field2,$field3) = split ";";
print "Finding photo for product: $product\n" if $Debug;
my $bestimage="<NONE>"; # Preset and overwrite if better one found
# Keep removing last character of product till it matches a photo
for(my $i=length($product);$i;$i--){
my $short = substr($product,0,$i);
print "Trying $short\n" if $Debug;
if(defined($photos{$short})){
$bestimage = $short . ".jpg";
last;
}
}
print "$product;$bestimage;$field3\n";
}