diff options
author | Guillermo Ramos | 2019-07-01 13:53:37 +0200 |
---|---|---|
committer | Guillermo Ramos | 2019-07-01 13:53:37 +0200 |
commit | d916ca90c354b29cc1b0953508e9601576a4fd1e (patch) | |
tree | f1997d85fb0736cfb0abdf4cb534f81df8220df3 /006 | |
parent | 85d335507fbb74df316bd5831e621e1a37884c35 (diff) | |
download | perlweekly-d916ca90c354b29cc1b0953508e9601576a4fd1e.tar.gz |
[all] Formatting, missing comments in header, etc
Diffstat (limited to '006')
-rwxr-xr-x | 006/ch1.pl | 45 |
1 files changed, 25 insertions, 20 deletions
@@ -1,34 +1,39 @@ #!/usr/bin/env perl +# +# Create a script which takes a list of numbers from command line and print the +# same in the compact form. For example, if you pass “1,2,3,4,9,10,14,15,16” +# then it should print the compact form like “1-4,9,10,14-16” +################################################################################ use strict; use warnings; sub compact { - my @ns = split(/,/, shift); - my $from = my $to = shift @ns; # The first interval is the first number - my @intervals; + my @ns = split(/,/, shift); + my $from = my $to = shift @ns; # The first interval is the first number + my @intervals; - # Store the current interval ($from, $to) and advance to the next one - my $save = sub { - push(@intervals, $from == $to ? $from : "$from-$to"); - $from = $to = shift; - }; + # Store the current interval ($from, $to) and advance to the next one + my $save = sub { + push(@intervals, $from == $to ? $from : "$from-$to"); + $from = $to = shift; + }; - # Iterate over the numbers, expanding the last interval or starting a new one - foreach my $n (@ns) { - if ($to == $n-1) { - $to = $n; - } else { - &$save($n); - } - } + # Iterate over the numbers, expanding the last interval or starting a new one + foreach my $n (@ns) { + if ($to == $n-1) { + $to = $n; + } else { + &$save($n); + } + } - # Store the last interval (except for empty input) - &$save if defined $to; + # Store the last interval (except for empty input) + &$save if defined $to; - return join(",", @intervals); + return join(",", @intervals); } foreach (@ARGV) { - print compact($_), "\n"; + print compact($_), "\n"; } |