2

I have an array of elements, which i need to store in separate cells using Perl file handling.

foreach(@type)
{
print FH qq|"@type","@date","@loc","@title"\n|;
}

I use the above code, but its only stores last element in the array.

Thanks in advance.

1
  • all variable have same number of values Commented Aug 5, 2013 at 12:38

2 Answers 2

6

If you use foreach (@type), the special variable $_ is assigned the values of @type one after one. In your code, you are not using the variable $_. On the contrary, you output @type, the array you are iterating over. You probably wanted to iterate over the indexes, something like

for (0 .. $#type) {
    print FH qq("$type[$_]","$date[$_]","$loc[$_]","$title[$_]"\n);
}

or, with a named loop variable:

for my $index (0 .. $#type) {
    print FH qq("$type[$index]","$date[$index]","$loc[$index]","$title[$index]"\n);
}

Note that if your columns might contain newlines or double quotes, you would be better off with Text::CSV.

Sign up to request clarification or add additional context in comments.

Comments

2

If you are trying to write a CSV file, it's a good idea to use a specific module from CPAN that will helps you a lot. For example, Text::CSV. There are a lot of small details you may forget in a custom implementation of the CSV format.

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.