数组 – Perl:将元素推送到数组中用新的变量值替换现有值
发布时间:2020-12-16 06:23:25 所属栏目:大数据 来源:网络整理
导读:我正在读取一个csv文件,需要将行中的值(第4行)作为数据库中的关键元素.但该行包含逗号分隔的多个值. 我使用Text :: CSV解析文件并将值拆分为第4行. 然后将这些值推入数组并插入到新文件中,以保持其他值相同. 但是在下一轮循环中,值将被新值替换. 因此,我最终
我正在读取一个csv文件,需要将行中的值(第4行)作为数据库中的关键元素.但该行包含逗号分隔的多个值.
>我使用Text :: CSV解析文件并将值拆分为第4行. 代码 : 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]]; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |