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!

Print array with comma separating elements 2

Status
Not open for further replies.

Extension

Programmer
Nov 3, 2004
311
0
0
CA
Hi,

I'm trying to find a simple way to print an array with a comma separating each element.
But a need a way to apply "styles" specific to each element; <span class="{style}"> before, and </span> after each element.
Is it possible to use the "print join" and still be able to apply specific "styles" to each element ?

I could always loop around each elements, but I wanted to know if there's a simple way to do this.

Array
Code:
@array = ("Red","Blue","Green","Purple");

Expected results
Code:
<span class="Red">Red</span>, <span class="Blue">Blue</span>, <span class="Green">Green</span>, <span class="Purple">Purple</span>

This won't work if I want to apply something to each element
Code:
print join(', ', @array), "\n";
 
Something like this might work for you:
Code:
@array = ("Red","Blue","Green","Purple");
print join(', ', map {"<span class=\"$_\">$_</span>"} @array), "\n";
 
map will apply a change to each element of an array, so you can use something like
Perl:
use strict;
use warnings;

my @colours = qw{Red Blue Green Yellow Purple};

print join(', ', map {"<span class=\"" . lc($_) . "\">$_</span>"} @colours), "\n";
to do what you want. But as you seem to be creating (X)HTML, I don't see what the commas are for. I've lower-cased the text to use in the class names, as you may not want the class names to be mixed case. Another possibility, if your class names don't match the data or you need to map multiple values onto the same class, would be to use a hash to map them over to the class names.
Perl:
my %colour_map = qw{red red pink red blue blue yellow green green green purple blue};

print join(', ', map {"<span class=\"" . $colour_map{lc($_)} . "\">$_</span>"} @colours), "\n";

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Nice solution rharsh, the only thing wrong with it is that you beat me to it by ONE minute [wink]

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Thanks to both of you for the help. Really appreciated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top