我正在讀取csv文件,並且需要將行(第4行)中的值作爲數據庫中的關鍵元素。但該行包含逗號分隔的多個值。Perl:將元素推入到數組中用新變量值替換現有值
我使用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; }
自卸車結果是:
因此我
的代碼(例如低於2)結束了的最後一個值的數組中的許多實例
#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提供了一個更好的方法來執行相同或更簡單的操作。 – norbdum