什么是perl中的@ $ varname

时间:2014-07-03 06:34:19

标签: perl sorting csv

我必须编写一个csv排序代码,我使用了以下代码:

foreach(@files){
    if(/\.csv$/i) { # if the filename has .csv at the end
        push(@csvfiles,$_);
    }
}

foreach(@csvfiles) {
    $csvfile=$_;
    open(hanr, "D:\\stock\\".$csvfile)or die"error $!\n"; # read handler
    open(hanw , ">D:\\stock\\sorted".$csvfile) or die"error $! \n"; # write handler for creating new sorted files
    @lines=();
    @lines=<hanr>;

    foreach $line (@lines){
        chomp $line;
        $count++;
        next unless $count; # skip header i.e the first line containing stock details
        my $row;
        @$row = split(/,/, $line );
        push @$sheet2 , $row;
    }

    foreach my $row (
      sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @$sheet2
    ) # sorting based on date ,then stockcode
    {
        chomp $row;
        print hanw join (',', @$row ),"\n";
    }
    @$sheet2 = ();
    $count   = -1;
    close(hanw);
    close(hanr);
}

但是我不明白@ $ row是什么..所以我理解排序正常数组@ sheet2比较第0列和第1列..但是如果有人会解释整个事情那就太棒了:

    @$row = split(/,/, $line );
    push @$sheet2 , $row;
}

foreach my $row ( sort {$a->[0] cmp $b->[0] || $a->[1] cmp $b->[1]}  @$sheet2 )
{
    *print hanw join (',', @$row ),"\n";
}

2 个答案:

答案 0 :(得分:3)

您有my $row;$row未定义,推入@$row(或@{$row})会自动创建新的数组autovivification perl功能。

如果是

sort {
  $a->[0] cmp $b->[0] || 
  $a->[1] cmp $b->[1]
}
@$sheet2

@$sheet2是数组结构数组,@$sheet2数组按子数组中的第一个和第二个元素排序(字符串排序到期cmp运算符;如果$a->[0]$b->[0]等于$a->[1]并且$b->[1]被比较)。

答案 1 :(得分:1)

@$row取消引用数组引用。

sort {$a->[0] cmp $b->[0] || $a->[1] cmp $b->[1]}这将比较两个数组中的第一个条目,如果它们相等,则将比较第二个条目。

希望这有帮助。