如何修改Perl脚本以根据版本在不同的目录中移动包?

时间:2012-04-07 19:15:45

标签: perl

我有这个Perl脚本,用于根据包版本对包进行排序:

#!/usr/bin/perl -w
#
# Compare versions of all *.rpm files against the
# latest packages installed (if installed)
#
# Usage:
# rpmver.pl
# This script looks for all *.rpm files.
#
use strict;
use RPM2;
my $rpm_db = RPM2->open_rpm_db();
for my $filename (<*.rpm>) {
    my $h = RPM2->open_package( $filename );
    # Ensure we compare against the newest
    # package of the given name.
    my ($installed) =
      sort { $b <=> $a } $rpm_db->find_by_name($h->name);
    if (not $installed) {
        printf "Package %s not installed.\n", $h->as_nvre;
    } else {
        my ($result) = ($h <=> $installed);
        if ($result < 0) {
            printf "Installed package %s newer than file %s\n",
            $installed->as_nvre,
            $h->as_nvre;
        } else {
            printf "File %s newer than installed package %s\n",
            $h->as_nvre,
            $installed->as_nvre;
        }
    }
 } 

我有一个带有SRPM的Linux存储库。我想把最新的包移到不同的目录中;例如latest_packages。如何修改脚本?

1 个答案:

答案 0 :(得分:1)

首先,将所有现在最新的包名称存储在名为%latest_package的哈希中;然后检查所有包后循环哈希的键并移动那些最新的包。

} else {
    printf "File %s newer than installed package %s\n", ...
    $latest_package{$h->name} = $installed->as_nvre;
    ...
}

使用File::Copy模块的move()方法移动文件。不要忘记将其视为任何其他IO系统调用(die,如果它出错,包括$!错误文本变量的内容;或使用autodie)。

foreach my $name (sort keys %latest_package) {
    File::Copy::move($latest_package{$name}, $LATEST_PACKAGE_DIR) 
        || die "Could not move $latest_package{$name} to $LATEST_PACKAGE_DIR: $!);
}

如果需要,使用mkdir()函数创建目录。