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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

foreach print question 2

Status
Not open for further replies.

ability1

Programmer
Dec 24, 2002
23
0
0
US
How would you go about printing the results of foreach of an array, alternating the color of HTML between gray and white for each line. For example

foreach $p_category (@p_categories){
print &quot;<tr><td bgcolor=\&quot;gray\&quot;> my results line 1 </td></tr>&quot;;

}

That's simple enough for all the results with a gray background but how to alternate?
 
Though not the exact code you would use, here is the logic that will do what you are looking for. Just adapt it to fit your needs.

@p_categories = qw (top of the morning to you on this fine lovely day);
$i = 0;
foreach $p_category (@p_categories){
if ($i == 0) {
$color = &quot;gray&quot;;
print &quot;$p_category $color\n&quot;;
$i = 1;
}
elsif ($i == 1) {
$color = &quot;white&quot;;
print &quot;$p_category $color\n&quot;;
$i = 0;
}
}

Cheers
 
Using raklet's code, I have a mod. This is a fun little task that comes up common enough, that I've done it several different ways. The funnest way (by far) was to set up a tied-scalar, and have it alternate it's value on each fetch. Alls I had to do was use it and it would automagically do the right thing.. .fun stuff. But, here's a quick way, without a tied var:
Code:
@p_categories = qw (top of the morning to you on this fine lovely day);

foreach $p_category (@p_categories){
                $color = ($color eq 'white')?'grey':'white';
                print &quot;$p_category $color\n&quot;;
}
--jim
 
i like that Coderifous - i'll remember that one!

another star...

Duncan
 
since you brought it up, here the one way I always use in my programs..

foreach $p_category ( @p_categories )
{
$color = $count++ % 2 ? 'gray' : 'white';
print &quot;<tr><td bgcolor=\&quot;$color\&quot;> my results line 1</td></tr>\n&quot;;
}

just one more way of doing it ;)

---
cheers!
san
pipe.gif


&quot;The universe has been expanding, and Perl's kind of been expanding along with the universe&quot; - Larry Wall
 
I always liked this approach. It'll let you cycle thru as many elements in a list as you want.
Code:
@colors = qw/white gray pink blue/;
$i = 0;
foreach $p_category (@p_categories)
{
	print &quot;$p_category $colors[$i]\n&quot;;
	$i = ($i + 1) % @colors
}
I think I used it before to play a little spinning &quot;please wait&quot; kind of animation of | / -
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top