Mike A Mike A - 1 month ago 24
Perl Question

Extract everything before second last hyphen in Perl

I'm trying to extract everything before second last hyphen in any given rpm. I have this working by specifying the index numbers, however this does not work for strings with a different number of hyphens. I know the release is after the last hyphen, the version is after the second last hyphen, and the name is everything before that. How can I do this with perl?

This is what I currently have:

my $str = "rpm-python-4.8.0-55";
my $name = join '-', (split /-/, $str)[-4 .. -3];
my $version = (split /-/, $str)[-2];
my $release = (split /-/, $str)[-1];

print "Name: $name\n";
print "Version: $version\n";
print "Release: $release\n";


Output:

Name: rpm-python
Version: 4.8.0
Release: 55

Answer

You can use the knowledge about the last two items, release and version.

my @items = split '-', $str;

my $release = pop @items;
my $version = pop @items;

my $package_name = join '-', @items;

Or, you can use a regex

my ($package, $version, $release) = $str =~ m/(.*)-([^-]+)-([^-]+)$/;