【问题标题】:Modifying a Perl script which has an error handling spaces in files修改文件中有错误处理空间的 Perl 脚本
【发布时间】:2013-08-14 20:19:57
【问题描述】:

我正在尝试使用用 Perl 编写的 here 脚本,但它遇到了错误。我已经联系了作者,但还没有回复。我希望你能帮助我。

错误如下:

错误:无法将 /home/bruno321/.config/Clementine/albumcovers/271b13967f57caba893b366730337fb03439c60a.jpg 复制到 /media/mp3_1/Musica/Amarok/Two%20Lone%20Swordsmen/A%20Bag%20of%20Blue%20Sparks/。错误:文件或目录不存在

我相信错误在于处理空格,因为在没有空格的目录中它运行正常,但是它不会像我相信脚本打算做的那样将文件重命名为“cover.jpg”(并且我当然需要它来做到这一点)。

#!/usr/bin/perl

use strict;
use warnings;
use Carp;

use DBI;
use strict;

use Data::Dumper;
use File::Basename;
use File::Copy;

my $db_filename = shift(@ARGV);
$db_filename
  || croak
"missing mandatory param: sqlite filename\n(try ~/.config/Clementine/clementine.db\n";

if ( !-f $db_filename ) {
    croak "no such database file: $db_filename\n";
}

my $force_rewrite = shift(@ARGV) || 0;

my $dbh =
  DBI->connect( "dbi:SQLite:$db_filename", q{}, q{},
    { 'RaiseError' => 1, 'AutoCommit' => 1 } );

my $query = q{SELECT artist,album, art_automatic,art_manual,filename
             FROM songs WHERE art_manual IS NOT NULL GROUP BY(album)  ORDER BY artist};

my $sth = $dbh->prepare($query);
$sth || croak 'prepare error: ' . $dbh->errstr . "\n";

$sth->execute || croak 'execute error: ' . $dbh->errstr . "\n";

my %treated = ();
while ( my $res = $sth->fetchrow_hashref ) {

    ( undef, my $dest_dir, undef ) = fileparse( $res->{'filename'} );

    next if $treated{$dest_dir};
    $treated{$dest_dir}++;

    # strip leading file://  -> should do this better
    $dest_dir =~ s/^file:\/\///g;

    my $dest_file = $dest_dir . 'cover.jpg';

    # unless we are given overwrite option, skip dirs that have covers
    if ( !$force_rewrite ) {
        next if ( -f $dest_file );
    }

    #print "CMD: cp $res->{'art_manual'} $dest_file\n";
    copy( $res->{'art_manual'}, $dest_dir )
      || printf( "ERROR: unable to copy %s to %s. error: %s\n",
        $res->{'art_manual'}, $dest_dir, $! );
}
exit;

【问题讨论】:

  • 该文件名中没有空格。错误信息很清楚;目标目录不存在。
  • @tripleee:但确实如此!好吧,至少用空格替换 %20 。更清楚地说,在几个没有空格的文件夹上它工作正常,除了它逐字复制文件而不是像我认为的那样将其重命名为“cover.jpg”。

标签: perl


【解决方案1】:

显然$dest_dir 是 URL 编码的,你需要它是文字的。换句话说,在修剪 file:// 前缀之后,您需要将任何 %NN 十六进制转义解码为相应的文字字符。见Using Perl, how do I decode or create those %-encodings on the web? 基本上,你想

use URI::Escape 'uri_unescape';

然后

$dest_dir = uri_unescape($dest_dir);

此外,您正在创建$dest_file,但随后忽略它并将文件复制到$dest_dir。

作为一个额外的风格问题,警告和错误应该发送到 stderr,而不是 stdout。

【讨论】:

  • 谢谢!我正在代码中修改它。我应该在哪里将$dest_dir 更改为$dest_file 以便将文件复制到我想要的位置?
  • 没关系,我在最后两个实例中更改了它,它产生了奇迹。非常感谢,三胞胎!
猜你喜欢
  • 2016-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
相关资源
最近更新 更多