1

i need to convert a perl array to a single string variable, containing all array items separated with newlines.

my $content = "";
@names=('A','C','C','D','E');
$content = $content . join($", @names) . "\n";
print $content;

I intend the output to be like:

A
C
C
D
E

But i get:

A C C D E

Why isn't the newline \n character being honoured?

4 Answers 4

6

Since it appears that you want a newline not just between each line, but after the last one too, you can use any of the following:

join("\n", @names) . "\n"
join("", map "$_\n", @names)
join("\n", @names, "")

These are equivalent except when the array in empty. In that situation, the first results in a newline, and the other result in an empty string.


By the way,

 $content = $content . EXPR;

can be written as

 $content .= EXPR;
Sign up to request clarification or add additional context in comments.

2 Comments

There is a slight difference: If the array is empty, join("", map "$_\n", @names) produces "", not "\n".
I usually just do e.g. join("\n", @array, "")
3

To join an array with newlines in between, use

join("\n", @array)

Your code uses the contents of the $" variable as the separator, which by default contains a space.

Comments

1

Do this instead:

$content = $content . join("\n", @names);

Comments

1

The $" variable holds the value that Perl uses between array elements when it interpolates an array in a double-quoted string. By default (and you haven't changed it), it's a space.

Perhaps you were thinking about the input or output record separators, $/ or $\.

But, you don't really want to play with those variables. If you want a newline, use a newline:

join "\n", @array;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.