tags:

views:

117

answers:

2

I have an array of strings that I would like to use the join function on. However, I would like to prefix each string with the same string. Can I do this in one line as opposed to iterating through the array first and changing each value before using join?

Actually it's a lil bit trickier. The prefix is not part of the join separator. Meaning if you used a prefix like "num-" on an array of (1,2,3,4,5), you will want to get this result: num-1,num-2,num-3,num-4,num-5

+3  A: 

Just make the prefix part of the join:

my @array = qw(a b c d);
my $sep = ",";
my $prefix = "PREFIX-";
my $str = $prefix . join("$sep$prefix", @array);

You could also use map to do the prefixing if you prefer:

my $str = join($sep, map "$prefix$_", @array);
runrig
Why are you storing a single string into an array?
cjm
cjm: Why are there bugs in code? Anyway, fixed :-)
runrig
+11  A: 

This code:

my @tmp = qw(1 2 3 4 5);
my $prefix = 'num-';
print join "\n", map { $prefix . $_ } @tmp;

gives:

num-1
num-2
num-3
num-4
num-5
simplemotives
I was going to post an answer, but yours is the best, so instead I fixed your formatting. :)
Ether
Changed it to use the less confusing block form of map, hope you don't mind :)
rjh
Sorry for the one-liner. Thanks for the edits.
simplemotives