我正在读取一个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; }
翻车机结果是:
#comment: this is Dumper $row result of first run in loop $VAR1 = [ 'Vehicle Factory','ajj137035','mdb650204' ]; #comment: this is the Dumper @newRows result of first run in loop $VAR1 = [ 'Vehicle Factory','mdb650204' ]; #comment: this is the Dumper $row result of 2nd run in loop $VAR1 = [ 'Vehicle Factory',' mgp657301','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','mdb650204' ]; $VAR2 = $VAR1;
解决方法
$row是对数组的引用.你反复将这个引用推到@newRows上,所以@newRows最终将拥有一组指向同一个东西的指针.每次推入@newRows时都需要复制数组
例如
my @arr = (1,2,3); my $ref_a = \@arr; my $ref_b = \@arr; $ref_a->[0] = "test"; print $ref_b->[0]; # prints "test";
附:你过分复杂了:
my @row = ('Vehicle Factory',...',...); my @newRows = (); for my $k (split /,\s*/,$row[3]) { push @newRows,[@row[0..2],$k,@row[4..$#row]]; }