Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn an array into a string

Tags:

arrays

perl

Okay, so I have an array that looks like this:

@foo = ("a","b","c","d");

... and a string stored in a variable as such:

my $foo = "e";

I want to turn this into a string that looks like this:

"e/a;e/b;e/c;e/d"

In other words, I'd like to add "$foo/" to the beginning of each array element and turn it into a string separated by semicolons. How can I do this?

like image 848
andrejr Avatar asked Mar 04 '26 17:03

andrejr


1 Answers

map and join

use warnings;
use strict;

my @foo = ("a","b","c","d");
my $foo = "e";
my $s = join ';', map { "$foo/$_" } @foo;
print "$s\n";

Output:

e/a;e/b;e/c;e/d
like image 77
toolic Avatar answered Mar 06 '26 16:03

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!