CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



iammgg
Novice

May 25, 2017, 1:19 AM

Post #1 of 3 (912 views)
Perl program that accepts integer argument Can't Post

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

Post #2 of 3 (902 views)
Re: [iammgg] Perl program that accepts integer argument [In reply to] Can't Post

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

Post #3 of 3 (900 views)
Re: [Laurent_R] Perl program that accepts integer argument [In reply to] Can't Post

Thanks so much. It works!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives