Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use File::Slurp to write an array to a file with newlines?

Tags:

perl

I am using File::Slurp to write to a file. The problem is that the array elements are being written as a single string on one line. I would like to print array elements on separate lines.

I can always format my array elements to have a newline in each element, which I don't want to do.

Does File::Slurp support any options to print array elements on separate lines? I don't find any options in the documentation.

use File::Slurp;
my @input = ();

push (@input, "1:2");
push (@input, "a:b");

write_file("./out", @input);

Output looks like this

1:2a:b

I want

1:2
a:b
like image 949
sam Avatar asked Dec 11 '13 21:12

sam


2 Answers

I don't think File::Slurp has an option to print array elements on separate lines. Use map to add newlines to all your array elements. This does not modify your array:

use warnings;
use strict;
use File::Slurp;

my @input = ();

push (@input, "1:2");
push (@input, "a:b");

write_file("./out", map { "$_\n" } @input);
like image 65
toolic Avatar answered Oct 19 '22 08:10

toolic


In this case, just set Perl's $" variable to \n and write the interpolated array to the file:

use strict;
use warnings;
use File::Slurp;

local $" = "\n";

my @input = ();
push( @input, "1:2" );
push( @input, "a:b" );

write_file( "./out", "@input" );

Output to file:

1:2
a:b
like image 7
Kenosis Avatar answered Oct 19 '22 09:10

Kenosis