Hi
I have need of printing a series of numbers. Any number in a series should be printed as "3-5" instead of "3,4,5". I have a working solution but it's kinda ugly. I was hoping that someone has an idea about how to improve it.
use strict; use warnings; my @list = sort {$a <=> $b} (1, 2, 3, 6, 9, 10, 13, 22, 20, 19, 15, 21 +); printf "%s\n", join(",", @list); my @newList; my ($min, $max); my $count = 0; foreach(@list) { if(! defined($min)) { $min = $_; $max = $_; } elsif($_ == ($max + 1) && $count != $#list) { $max++ } else { if($min == $max) { push @newList, ($min, $_) } else { push @newList, ("$min-$max", $_) } $min = undef; $max = undef; } $count++; } printf "%s\n", join(",", @newList);
Added a list instead of printing it, looks nicer.
But Im still waiting for the one liner that is easy to understand and amazes us all :D
In reply to Print series of numbers by mickep76
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |