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

Hi monks i have a little question which hopefully u cud help with. i am trying to compare versions of some software and they are in a string of X.Y.Z format. so to compare these versions i thought of using substring but the problem that arises is that the format can be in a X.YY.Z or X.Y.ZZ format as well i was hoping to use regular expressions for this but i could only find expressions to match strings and not to grab certain parts of the string.
#!/usr/bin/perl # Checking of ETS version my $version; open (VERSION,'path'); while (<VERSION>){ $version=$_; chomp ($version); } my ($X,$Y,$Z); if ($version =~ /(\d\.\d\.\d)/) { $X = substr $version, 0, 1,; $Y = substr $version, 3, 4,; $Z = substr $version, 6, 7,; } elsif($version =~ /(\d\.\d\d\.\d)/) { $X = substr $version, 0, 1,; $Y = substr $version, 3, 5,; $Z = substr $version, 7, 8,; } elsif($version =~ /(\d\.\d\.\d\d)/) { $X = substr $version, 0, 1,; $Y = substr $version, 3, 4,; $Z = substr $version, 7, 9,; } elsif($version =~ /(\d\.\d\d\.\d\d)/) { $X = substr $version, 0, 1,; $Y = substr $version, 3, 5,; $Z = substr $version, 7, 9,; } print "X,Y,Z Values are $X,$Y,$Z";


pls note that as of nw i am only trying to get the values from the string and nothing else. and as u can see it is nt a very efficient way of doing it. i was hoping u monks would have a better idea of doing it efficiently

Replies are listed 'Best First'.
Re: regular Expression
by toolic (Bishop) on Mar 15, 2011 at 18:30 UTC
    See perlre (Capture buffers).
    use warnings; use strict; while (<DATA>) { if (/ ^ (\d+) [.] (\d+) [.] (\d+) $ /x) { print "$1 $2 $3\n"; } } __DATA__ 7.55.3 12.0.2
    Prints:
    7 55 3 12 0 2

    Update: I noticed your update, and maybe you want to restrict it to 1- or 2-digit only:

    if (/ ^ (\d{1,2}) [.] (\d{1,2}) [.] (\d{1,2}) $ /x) {
Re: regular Expression
by ikegami (Patriarch) on Mar 15, 2011 at 18:45 UTC
Re: regular Expression
by umasuresh (Hermit) on Mar 15, 2011 at 18:27 UTC
    Would this help
    my ($x,$y,$z) = $version =~/(\w+)\.(\w+)\.(\w+)/;
    Note: untested, need an example of $version!
Re: regular Expression
by repellent (Priest) on Mar 16, 2011 at 04:34 UTC
    my $is_later = ( version->parse("1.23.4") > version->parse("5.6.78") );

    Example:
    use warnings; use strict; for my $vs ( [ qw( 1.1.1 1.01.1 ) ], [ qw( 1.23.4 1.22.4 ) ], [ qw( 1.23.4 2.02.1 ) ], [ qw( 1.3.42 1.02.1 ) ], [ qw( 8.27.32 8.27.17 ) ], ) { my ($v1, $v2) = map { version->parse($_) } @{ $vs }; my $c = $v1 == $v2 ? "==" : $v1 > $v2 ? ">" : "<"; print "$v1 $c $v2\n"; } __END__ 1.1.1 == 1.01.1 1.23.4 > 1.22.4 1.23.4 < 2.02.1 1.3.42 > 1.02.1 8.27.32 > 8.27.17