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.
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 .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.