Home: Perl Programming Help: Beginner:
variable declaration and countdown



jazzo
Novice

Aug 25, 2012, 10:41 AM


Views: 1481
variable declaration and countdown

Hi peeps, I came across this simple script:

Code
 
#!/usr/bin/perl
# countdown.plx
use warnings;
use strict;
my @count = (1..5);
for (reverse(@count)) {
print "$_...\n";
sleep 1;
}
print "BLAST OFF!\n";

and I was wondering, shouldn't the variable

Code
reverse

be declare as

Code
my reverse

rather than using it without declaring it?
The the other thing. to print off the numbers we say:

Code
print "$_...\n";

why do we use "$_"?
can we not use the array something like

Code
print "$count[reverse]\n";

thanks


(This post was edited by jazzo on Aug 25, 2012, 10:48 AM)


FishMonger
Veteran / Moderator

Aug 25, 2012, 11:03 AM


Views: 1478
Re: [jazzo] variable declaration and countdown

reverse is not a variable. It's one of perl's built-in functions.

http://perldoc.perl.org/functions/reverse.html


Laurent_R
Veteran / Moderator

Aug 25, 2012, 11:05 AM


Views: 1477
Re: [jazzo] variable declaration and countdown

Hi,

reverse is not a variable, but a function that reverse the order of the @count array (makes it 5 4 3 2 1).

In the for loop, the default variable $_ is assigned successively to the reversed values of @count.

You could write this more explicitly:


Code
foreach my $number (reverse @count) { 
print "$number...\n";
sleep 1;
}
print "BOOOOM\n";



jazzo
Novice

Aug 25, 2012, 11:23 AM


Views: 1473
Re: [Laurent_R] variable declaration and countdown

of course it is a function, what a donkey I am, sorry!