Product SiteDocumentation Site

Iterating over packages

Iterators are important in the RPM2 package because they provide a more efficient interface to potentially large sets of packages, and because iterators more closely match the underlying C API. Furthermore, iterators are very easy to use. Simply call the next subroutine to move ahead to the next element, that is, the next package.
For example:
my $pkg_iter = $rpm_db->find_by_name_iter( "kernel" );
while (my $pkg = $pkg_iter->next() ) {
# Do something ...
}
Listing 18-3 shows a script that acts much like the rpm –q command, without any other command-line options.
Listing 18-3: rpmname.pl
#!/usr/bin/perl
#
# Queries RPM database for given package.
# Usage:
# rpmname.pl package_name
#
use strict;
use RPM2;
my $rpm_db = RPM2->open_rpm_db( "−path" => "/var/lib/rpm" );
my $pkg_iter = $rpm_db->find_by_name_iter( $ARGV[0] );
while (my $pkg = $pkg_iter->next() ) {
print $pkg->tag("NAME"), "-", $pkg->tag("VERSION"), "\n";
}
$rpm_db->close_rpm_db();
When you run this script, you need to pass the name of a package to query. For example:
$ ./rpmname.pl kernel
kernel-2.4.18