[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 256
  • Last Modified:

Create csv file with array

I have this array:

@du_each = (150MB, /data/home/foo, 100MB, /data/home/foo/bar.txt, 50MB, /data/home/foo/bar2.txt....etc)

I want to output this to a .csv file. Where every two elements is a row. So the output would be:

150MB, /data/home/foo
100MB, etc.

I'm not sure how to start this. I was thinking looping through the array and adding a \n character after two elements. Am I headed in the right direction? There must be an easier way that what I have below which I don't think is correct...

for (my $j = 1; $j <= ($#du_each -2); $j+=2){
        @csv_out = join('\n',$du_each[$j]);
        print "@csv_out\n";

Any help is appreciated. Thanks.
2 Solutions
The easiest way would be if you could change @du_each to look like:

@du_each = ([150MB, /data/home/foo], [100MB, /data/home/foo/bar.txt], ...)

Then you could simply do:

print map { "$_->[0],$_->[1]\n" } @du_each;

If @du_each has to stay like it is, this is the simplest I can come up with off the top of my head:

while (@du_each) {
    my $sz = shift;
    my $dir = shift;
    print "$sz,$dir\n";

Alternately, to modify your current looping style:

for (my $i = 0; $i < @du_each; $i += 2) {
    print join(',', @du_each[$i..$i+1]), "\n";

Actually if @du_each has to stay the same, the second option ended up being cleaner than my first thought...
An easy look would be something like this
This is just an example, I know you will have more items in your array
@du_each = ('150MB', '/data/home/foo', '100MB', '/data/home/foo/bar.txt', '50MB', '/data/home/foo/bar2.txt');
my $count=1;
while (@du_each."" > 0 )
    print shift @du_each;
    if ($count%2 == 0)
        print "\n";
        print ",";
    $count = $count+1;

Open in new window


@du_each = ('150MB', '/data/home/foo', '100MB', '/data/home/foo/bar.txt', '50MB', '/data/home/foo/bar2.txt');
print join(', ',splice @du_each,0,2),"\n" while @du_each;
akatsuki27Author Commented:
Thanks guys, all those options worked. I'll go with ozo's because it's only 1 line.

Thanks ozo.

Now to be able to output this to the csv file it's simply this, no?

open(FILE, "> $destination");
print FILE blah
print FILE join(',',splice @du_each,0,2),"\n" while @du_each;
close (FILE)


ozo's solution is only one line but is less efficient than my third possible solution since ozo's solution modifies the array on each pass through the loop (as does my second suggestion).  However, you are highly unlikely to notice the performance difference unless you have a *VERY* large array (and/or a *VERY* slow computer).

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now