【发布时间】:2014-02-27 12:50:20
【问题描述】:
我正在读取一个 csv 文件,需要将一行(第 4 行)中的值作为数据库中的关键元素。但该行包含多个以逗号分隔的值。
我使用 Text::CSV 解析了文件并将值拆分到第 4 行。
然后将这些值推入一个数组并插入到一个新文件中,保持其他值不变。
但在下一次循环运行中,该值被新值替换。
因此我最终得到了数组中最后一个值的尽可能多的实例(在下面的示例中为 2)
代码:
use Data::Dumper;
use strict;
my @oneRow = ('Vehicle Factory',
'D3',
'2518, 1613, 1512, 1109, 912 bus, 712 bus, 613 Export',
'ajj137035, mgp657301',
'ddb255570',
'mdb650204'
);
my $row = \@oneRow;
my @newRows;
my $userString = $row->[3];
my @userNewRow = split(/,/,$userString);
foreach(@userNewRow) {
$row->[3] =~ s/.*/$_/;
print Dumper $row;
push @newRows, $row;
print Dumper @newRows;
}
Dumper 结果是:
#comment: this is Dumper $row result of first run in loop
$VAR1 = [
'Vehicle Factory',
'D3',
'2518, 1613, 1512, 1109, 912 bus, 712 bus, 613 Export',
'ajj137035',
'ddb255570',
'mdb650204'
];
#comment: this is the Dumper @newRows result of first run in loop
$VAR1 = [
'Vehicle Factory',
'D3',
'2518, 1613, 1512, 1109, 912 bus, 712 bus, 613 Export',
'ajj137035',
'ddb255570',
'mdb650204'
];
#comment: this is the Dumper $row result of 2nd run in loop
$VAR1 = [
'Vehicle Factory',
'D3',
'2518, 1613, 1512, 1109, 912 bus, 712 bus, 613 Export',
' mgp657301',
'ddb255570',
'mdb650204'
];
#comment: this is Dumper @newRows result of second run in loop
the new value is inserted but the first value becomes same as new value
$VAR1 = [
'Vehicle Factory',
'D3',
'2518, 1613, 1512, 1109, 912 bus, 712 bus, 613 Export',
' mgp657301',
'ddb255570',
'mdb650204'
];
$VAR2 = $VAR1;
【问题讨论】:
-
更改了接受的答案,因为@aidan's 提供了一种更好的方法来做同样的事情或更简单。