in reply to eliding number ranges

You can do this with straight length and substr.

#!/usr/local/bin/perl -w use strict; while (<DATA>) { chomp; my ($from, $to) = split /\s+/; my $diff = $to - $from; # get the difference ($from, $to) = ($to, $from) if $diff < 0; # error checking if (!$diff) { print "$from\n"; } else { $to = substr($to, length($to) - length($diff)) if length($diff) < length($from) and substr($from, 0, 1) eq substr($to, 0, 1); print "$from-$to\n"; } } __DATA__ 1 32 4 19 28 39 34 123 321 321 324 329 325 349 340 509 51 1
And the output -
1-32 4-19 28-39 34-123 321 324-9 325-49 340-509 1-51
Update: Thanks Abigail-II I have fixed the bug in the code.

Replies are listed 'Best First'.
Re: Re: eliding number ranges
by qq (Hermit) on Nov 14, 2003 at 11:13 UTC

    I knew that I was maknig it more complicated than needed. This seems like the cleanest approach so far - although the xor trick is pretty nice.

    Thanks everyone for the as-ever illuminating responses.

    qq

Re: eliding number ranges
by Abigail-II (Bishop) on Nov 14, 2003 at 11:34 UTC
    This line smelled very fishy to me:
    $to = substr($to, length($to) - length($diff))
    And indeed, on the input 199 200, it prints 199-0.

    Abigail