Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a prefix when using join in Perl

Tags:

join

perl

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

like image 617
syker Avatar asked Apr 27 '10 22:04

syker


2 Answers

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
like image 55
racerror Avatar answered Oct 20 '22 23:10

racerror


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);
like image 26
runrig Avatar answered Oct 20 '22 22:10

runrig