Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question regarding the FOR loop

Status
Not open for further replies.
May 3, 2003
90
CA
Hello All,

Hope your enjoying your day so far.

It's a really simple question.

For the FOR loop, I would like for it to count backwards.

EX:

for (1 .. 5)
{
print "$_\n";
}

it prints
1
2
3
4
5

I would like for it to print this way

5
4
3
2
1

I already have a work around by inserting an extra variable.

But I would like to know if the loop itslef can count backwards.

Something like :

reverse(for( 1.. 5))
{
print "$_\n";
}

Thanks,
 
well, you can do

for (reverse(1..5)) {
print "$_\n";
}

but I wouldn't do it for huge numbers of iterations.

That code actually creates the list (1, 2, 3, 4, 5), reverses it, then does the loop for each member of the list. Creating a long array is a bad idea; creating a long array and reversing it is a REALLY bad idea. Quicker to use a counter.


Brad Gunsalus
bardley90@hotmail.com
 
here a bit that may help you:

my $count;
$| = 1;
for ($count = 300; $count >= 0; $count--){
printf("%3d",$count);
sleep 1;
print((chr 8)x3);
}
 
Code:
#!/usr/bin/perl

for ($x=5; $x>=1; $x--)
{
  print "$x\n";
}


Kind Regards
Duncan
 
yes duncdude,
this guy cannot think, not logic
but is
$x>=1
not the same as(4 readability ++ assumed
$x is a positive value)
$x >0
?
 
Hi TheGenius22

I really don't want to appear rude but you might want to get hold of a nice & simple book on learning Perl e.g. Perl in Easy Steps

A book like this will take you through all of the common Perl functions - without the heavier stuff. You'll get through it in no time as the suggestion you posted is more involved - therefore the examples will be a breeze for you. You can only have come at this problem from an awkward angle. Give it a shot.

As I said - I really do not intend this message to appear rude!


Kind Regards
Duncan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top