Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print the elements of an array repeated twice each side-by-side?

Tags:

perl

Please, I have the following line of code to write the header of a file, but I'd like to print each element of the array @order twice side-by-side. For example: $1 $1 $2 $2 $3 $3... in a way that I would have each pair of columns of my output file with the same name.

print(join("\t", "Case_ID", "State", "Ind", "DoB", @order) . "\n");

Can I do something simple or I have to loop over the array to repeat the elements before I print?

Thanks!

like image 289
vitor Avatar asked Oct 11 '12 22:10

vitor


People also ask

How do you check if an element appears twice in an array?

Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1). Find the element with positive value and return their index.

How do you repeat an element in an array Java?

Method 1 :Run a loop from index 0 to n and check if (visited[i]==1) then skip that element. Otherwise create a variable count = 1 to keep the count of frequency. Check if(arr[i]==arr[j]), then increment the count by 1 and set visited[j]=1.


1 Answers

You have to loop anyway, but you can use map for syntactic elegance:

# map { $_, $_ } @order


print join("\t", "Case_ID", "State", "Ind", "DoB", map { $_, $_ }  @order))
       . "\n";
like image 150
DVK Avatar answered Sep 28 '22 15:09

DVK