Perl:将哈希数组传递给子的最佳方法

时间:2017-05-15 21:55:36

标签: arrays perl

我的课程如下所示:

package CSVKeepCols;

use strict;
use warnings;
use Text::CSV;
use Data::Dumper;

my $text;
my $del;
my @cols;
my $output = '';

sub load {
    my $class = shift;
    my $self = {};
    bless $self;
    return $self;
}

sub input {
    my $class = shift;
    $text = shift;
    return $class;
}

sub setOpts {
    my ($class, $opts) = @_;
    $del  = $opts->{'delimeter'};
    @cols = $opts->{'columns'};
}

sub process {
    my @lines = split /\n|\r|\n\r|\r\n/, $text;
    my $csv = Text::CSV->new({ sep_char => $del });

    foreach (@lines) {
        die('Invalid CSV data') if !$csv->parse($_);
        $output .= __filterFields($csv->fields()) . "\n";
    }
}

sub output {
    return $output;
}

sub __filterFields {
    my @fields = @_;
    my $line = '';

    foreach (@cols) {
        $line .= ',' if $line;
        $line .= $fields[$_];
    }

    return $line;
}

1;

我在我的代码中使用这个类:

$parser = load CSVKeepCols();
$parser->input($out);
$parser->setOpts({'delimeter' => ',', 'columns' => [1,2]});
$parser->process();
$out = $parser->output();

我期待,setOpts子例程将采用哈希值{'delimeter' => ',', 'columns' => [1,2]},并从那里将$del的值设置为,,将@cols设置为(1,2)所以我可以遍历@cols数组。

但是,当我尝试在@cols子例程中循环__filterFields时出现错误

Use of reference "ARRAY(0x22e32e0)" as array index at CSVKeepCols.pm line 52.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

在setOpts中,设置@cols = $opts->{columns};

$opts->{columns}包含对数组的引用([1,2])。

所以在__filterFields中:

for ( @cols ){
   # $_ is an arrayref [1,2]
   # you are using it as an index to retrieve a value from @fields
   $line .= $fields[$_];
   # Thus the error: "use of reference ARRAY"..." as array index"
   # You should be using an integer here.
}

修复它:

sub setOpts {
   # ...
   @cols = @{ $opts->{columns} };

}

编辑:删除了不必要的支票