Perl Compare Strings without Numbers

I have 2 variables:

my $var1 = 'package-name-1.4';
my $var2 = 'package-name-1.5';

What I'm trying to do, is to compare $var1 to $var2, while excluding the numbers.

I have looked online and tried Regex but I can't get it working, I'd greatly appreciate some help.

What I have in mind is as follows:

if (removeNumbers($var1) =~ removeNumbers($var2))

So that the result would be like comparing: package-name- with package-name-, thus evaluating true.

Thanks in advance for your help!

Answers


Well, the easiest approach is just to remove all digits altogether:

sub remove_numbers {
  my ($orig) = @_;
  $orig =~ s/\d+//g;
  return $orig;
}

But it's a bit naïve: for example, some-package-1.4.1 and some-package-1.4 would be not equal. It's better to remove dots as well, but only if they follow digits (serving as separators).

  $orig =~ s/\d+[.]?//g;

Even more, perhaps the first hyphen that precedes the number should go also (so 'package-name' and 'package-name-1' (and even 'package-name-1.0-some-fancy-line' and 'package-name-some-fancy-line') would be treated the same:

  $orig =~ s/-?\d+[.]?//g;  

UPDATE: Yet there's more than one way to do it:

  $orig = substr $orig, 0, rindex $orig, '-';

It's applicable if all the strings have the same format (version numbers are always at the end of the string, always follow the last hyphen, which is always there):

Used as follows:

if (remove_numbers($var1) eq remove_numbers($var2))

Need Your Help

Counting rows with conditions?

php login counting login-script

Before you say it has been answered before, I have tried everything, literally.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.