A thousand pardon for this silly question (been away for a while)
I need to read in a list of numbers and make sure that the numbers start at 1 and increment by 1 until the end of the list. So...
1 2 3 4 5 would return a success.3 2 1 4 5 would return a success.2 3 1 1 6 would return a failure1 2 4 5 6 would return a failure
I have the following code (which works) and was wondering if there is another way of doing this.. I could not find a module on CPAN after a little search earlier today.
#! /usr/bin/perl
use strict;
use warnings;
print "Please enter a list of numbers (I.e. 1 2 3 4 5)\n";
chomp(my $n = <STDIN>);
my @numlist = split/\s/, $n;
@numlist = sort { $a <=> $b } @numlist;
if ($numlist[0] == 1) {
print "Horray Array starts at 1\n";
my $prevnum = 0;
foreach my $number (@numlist) {
unless (($prevnum + 1) == $number) {
print "Error in Sequence";
$prevnum = 0;
last;
}
else {
$prevnum = $number;
}
}
if ($prevnum) {
print "The numbers are correct\n";
}
}
else {
print "Error Array DOES NOT Start at 1\n";
}
P.S. the verbose code is to try and help with readability
-----
Of all the things I've lost in my life, its my mind I miss the most.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.