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 d开发者_运维知识库o 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
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
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);
精彩评论