Home: Perl Programming Help: Beginner:
Perl program that accepts integer argument



iammgg
Novice

May 25, 2017, 1:19 AM


Views: 1861
Perl program that accepts integer argument

Hello there. I have no idea about the reverse function so I did a research through the internet. My code doesn't work well when I try to execute it on the terminal.

The instruction is written inside.


Code
#!/usr/bin/perl 
use strict;
use warnings;

=pod
Write a perl program that will accept an integer argument
and output the example below,
use any kind of loops you prefer.

Example:
3.2_LoopTest.pl 5
5 4 3 2 1
Boom!!
=cut

if(@ARGV > 0) {
print "@ARGV\n";
foreach my $i (reverse(0..$#ARGV)) {
print "Boom!!\n";
}
}


Can you guys tell me what's wrong with this one? I know that there's something wrong because the output appears as:


Code
$ ./3.2_loopTest.pl 5 
5
Boom!!


instead of the output that was shown inside (comment) of the code.

thanks in advance.


(This post was edited by iammgg on May 25, 2017, 1:29 AM)


Laurent_R
Veteran / Moderator

May 25, 2017, 2:04 AM


Views: 1851
Re: [iammgg] Perl program that accepts integer argument

Hi,

$#ARGV contains the index of the last item in the @ARGV array. Since you pass only one parameter, it contains 0. You need to use instead the value passed to your program.

Also note that you're never printing $i, so that you will never see the count-down. And you need to print "Boom" after the end of the count-down.

Here is one way to do it:


Code
if(@ARGV > 0) {  
print "@ARGV\n";
my $param = shift; # or: my $param = $ARGV[0];
foreach my $i (reverse 0..$param) {
print "$i ";
}
print "\nBoom!!\n";
}



iammgg
Novice

May 25, 2017, 2:18 AM


Views: 1849
Re: [Laurent_R] Perl program that accepts integer argument

Thanks so much. It works!