Reputation: 19
I am encountering an issue while trying to execute a perl script that takes 2 number arguments, well say $ARGV[0] is 2, and $ARGV[1] is 4. I need to print a list that shows 2,3,4 with no comma after the last item. Below is my script as it is now:
unless ((@ARGV)==2){
print "error: incorrect number of arguments",
"\n",
"usage: inlist.pl a b (where a < b)",
"\n";
exit VALUE;
}
if ($ARGV[0] > $ARGV[1]){
print "error: first argument must be less than second argument",
"\n",
"usage: intlist.pl a b (where a < b)",
"\n";
exit VALUE;
}
else {
$COUNTER=$ARGV[0];
while($COUNTER <= $ARGV[1]){
print $COUNTER;
$COUNTER += 1;
if ($COUNTERELATIONAL < $ARGV[1]){
print ", ";
}
else {
print "\n";
}
$COUNTERSYNTAX
}
}
exit VALUE;
I tried using join but to no avail I keep getting as return of 2,3,4,
I feel like i must be missing something simple
Upvotes: 0
Views: 166
Reputation: 69314
Rewriting your code to simplify it:
# Prefer 'if' over 'unless' in most circumstances.
if (@ARGV != 2) {
# Consider using 'die' instead of 'print' and 'exit'.
print "error: incorrect number of arguments\n",
"usage: inlist.pl a b (where a < b)\n";
# Not sure what VALUE is, but I assume you've
# defined it somewhere.
exit VALUE;
}
if ($ARGV[0] > $ARGV[1]) {
# Consider using 'die' instead of 'print' and 'exit'.
print "error: first argument must be less than second argument\n",
"usage: intlist.pl a b (where a < b)\n";
exit VALUE;
}
# Removed 'else' branch as it's unnecessary.
# Use 'join' instead of a complicated loop.
print join(',', $ARGV[0] .. $ARGV[1]), "\n";
# This looks like a successful execution to me, so
# that should probably be 'exit 0'.
exit VALUE;
If I was writing it for myself, I'd make it a little shorter:
my %errors = (
NUMBER => 'incorrect number of arguments',
RANGE => 'first argument must be less than second argument',
);
my $usage = 'usage: inlist.pl a b (where a < b)';
die "$errors{NUMBER}\n$usage\n" if @ARGV != 2;
die "$errors{RANGE}\n$usage\n" if $ARGV[0] > $ARGV[1];
print join(',', $ARGV[0] .. $ARGV[1]), "\n";
exit 0;
Upvotes: 2
Reputation: 19
I figured it out:
while($COUNTER <= $ARGV[1]){
print $COUNTER;
$COUNTER += 1;
if ($COUNTER <= $ARGV[1]){
print ", ";
}
else {
print "\n";
}
I needed to change the if to $COUNTER and <= and it printed correctly. Thank you for the join suggestion, that would have worked if I had designed the script more efficiently
Upvotes: 0