6

I have columns in @columns:

my @columns =('column1', 'column2', 'column3');

and I have separators in @separators:

my @separators = (',', '|');

I want to insert the separators between columns, one by one:

column1,column2|column

my solution is:

(@columns »~» (|@separators,"")).join("")

Here I have three columns and two separators, and how about insert N-1 separators between N columns?

chenyf
  • 5,048
  • 1
  • 12
  • 35

3 Answers3

9

Assuming that @separators has the right number of values, you could use roundrobin.

roundrobin( @columns, @separators ).flat.join()
Community
  • 1
  • 1
Brad Gilbert
  • 33,846
  • 11
  • 78
  • 129
6

So this should work for a any length of @columns or @separators :

First we use the >>,>> hyper operator to make a list of lists.

(@columns >>,>> @separators)

Which gives :

[("column1", ","), ("column2", "|"), ("column3", ",")]

Then we flatten this into a single list using a slip.

(@columns >>,>> @separators).map( |* )

Which gives:

("column1", ",", "column2", "|", "column3", ",").Seq

Then we get the array of all but the last value :

(@columns >>,>> @separators).map(|*).head(*-1)

For :

("column1", ",", "column2", "|", "column3")

And finally join it with nothing :

(@columns >>,>> @separators).map(|*).head(*-1).join("")

Final result :

column1,column2|column3

Changing the number of columns or separators will not make a difference.

Scimon Proctor
  • 4,558
  • 23
  • 22
0

May be another solution:

my @columns =('column1', 'column2', 'column3');
my @separators = (',', '|');
sub sep { $^a ~@separators[$++] ~$^b};
say [[&sep]] @columns;

say [[&sep]] @columns; # but another call cause error


Use of uninitialized value of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something     meaningful.
in sub sep at <unknown file> line 1
in block <unit> at <unknown file> line 1

Use of uninitialized value of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to something  meaningful.
in sub sep at <unknown file> line 1
in block <unit> at <unknown file> line 1

column1column2column3
chenyf
  • 5,048
  • 1
  • 12
  • 35