USP45 has asked for the wisdom of the Perl Monks concerning the following question:

This may not necessarily be a Perl question maybe a programming logic question in general but I have faith perl can figure it out. There's a list of version numbers (e.g. 1.0.0.0 1.1.10.1 2.0.0.0 2.1.0.0 10.6.1.0). There's a minimum and maximum (e.g. 2.0.0.0 and 3.0.0.0). How do I get a list of the versions that equal or fall in between the min and max? (output would be 2.0.0.0 2.1.0.0). --- I think the first step is splitting the numbers out into an array each since you can't compare them as-is. Then maybe iterate through. But I can't quite get the solution...

Replies are listed 'Best First'.
Re: Version list with min and max
by TGI (Parson) on Feb 23, 2008 at 02:53 UTC

    You should take a look at the version module. It gives you standard comparison operators so you can just do this:

    use version; my $max = qv( "3.0.0.0" ); my $min = qv( "2.0.0.0" ); my @versions = ( qv("1.0.0.0"), qv("1.1.10.1"), qv("2.0.0.0"), qv("2.1.0.0"), qv("10.6.1.0"), ); my @constrained_versions = grep { $max >= $_ and $min <= $_ } @versions; print "@constrained_versions\n";


    TGI says moo

      That should be ge and le rather than >= and <=.

      Update: Both should work.

Re: Version list with min and max
by hipowls (Curate) on Feb 23, 2008 at 01:54 UTC

    Assuming the individual numbers are in the range 0 - 255 then you can do this

    my $min = canonical('2.0.0.0'); my $max = canonical('3.0.0.0'); my @versions = qw(1.0.0.0 1.1.10.1 3.1 2.0.1 1.9.9.9.9 3.0.0.0.0.0.0.1 + 2.9 2.0.0.0 2.1.0.0 10.6.1.0); foreach my $version ( @versions) { my $canonical = canonical($version); print "$version\n" if ( $min le $canonical && $canonical le $max ) +; } sub canonical { return pack 'C*', split /\./, $_[0]; } __END__ 2.0.1 2.9 2.0.0.0 2.1.0.0

    Update: removed assumption that the version strings need to have the same number of numbers.

Re: Version list with min and max
by jasonk (Parson) on Feb 23, 2008 at 17:43 UTC

    There is a CPAN module for everything...

    use Sort::Versions; my $min = '2.0.0.0'; my $max = '3.0.0.0'; my @list = qw( 1.0.0.0 1.1.10.1 2.0.0.0 2.1.0.0 10.6.1.0 ); for my $entry ( @list ) { next if versioncmp( $entry, $min ) < 0 or versioncmp( $entry, $max ) > 0; print "$entry is between $min and $max\n"; }

    We're not surrounded, we're in a target-rich environment!
Re: Version list with min and max
by apl (Monsignor) on Feb 23, 2008 at 13:51 UTC
    You're right, it's not a Perl problem. Don't worry about the implementation of the solution, think about the algorithm of the solution. Say your teacher handed you a list of version numbers... how would you determine whether or not one fell within the minimum and maximum?
Re: Version list with min and max
by USP45 (Novice) on Feb 24, 2008 at 00:00 UTC
    Thanks all. I'm still so impressed with the perl community.