gpt4 book ai didi

arrays - Perl:将元素插入数组用新的变量值替换现有值

转载 作者:行者123 更新时间:2023-12-05 00:26:30 25 4
gpt4 key购买 nike

我正在读取一个 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',
    '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;

    最佳答案

    $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', 'D3', '2518, ...', ...);
    my @newRows = ();

    for my $k (split /,\s*/, $row[3])
    {
    push @newRows, [@row[0..2], $k, @row[4..$#row]];
    }

    关于arrays - Perl:将元素插入数组用新的变量值替换现有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22058933/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com