We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Create csv file with array

akatsuki27
akatsuki27 asked
on
Medium Priority
266 Views
Last Modified: 2012-08-14
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.
Comment
Watch Question

CERTIFIED EXPERT
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
CERTIFIED EXPERT

Commented:
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";
    }
    else
    {
        print ",";
    }
    $count = $count+1;
}

Open in new window

ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

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)

CERTIFIED EXPERT

Commented:
Correct.

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).
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.