从perl数组中获取多个值的最佳方法是什么?

时间:2011-09-09 23:16:25

标签: perl

例如,

首先,我将dataRecord放入这样的数组中,

  my @dataRecord = split(/\n/);

接下来,我对数组数据记录进行过滤,得到像这样的测试行,

  @dataRecord = grep(/test_names/,@dataRecord);

接下来,我需要从测试行获取测试名称,

   my ($test1_name,$test2_name,$test3_name)  = getTestName(@dataRecord);

   sub getTestName
   {
       my $str = shift @_;
       # testing the str for data and 
       print str,"\n"; # This test point works in that I see the whole test line.
       $str =~ m{/^test1 (.*), test2 (.*), test3 (.)/};
       print $1, "\n"; # This test point does not work. 
       return ($1,$2,$3);
    }

我有更好的方法来完成这项任务吗?

2 个答案:

答案 0 :(得分:4)

您可以将操作链接在一起,同时减少所需的语法。这有利于强调程序的重要部分,同时减少语法噪音。

my @test = map m{/^test1 (.*), test2 (.*), test3 (.)/},
           grep /test_names/,
           split /\n/;

# use $test[0], $test[1], $test[2] here

如果您正在尝试调试问题,map和grep可以使用块,从而可以轻松插入错误检查代码:

my @test = map {
               if (my @match = m{/^test1 (.*), test2 (.*), test3 (.)/}) {
                   @match
               } else {
                   die "regex did not match for: $_"
               }
           } # no comma here
           grep /test_names/,
           split /\n/;

以下是一些从数组中分配的与您的问题没有直接关系但可能有用的方法:

my ($zero, $one,  $two) = @array;
my (undef, $one,  $two) = @array;
my (undef, undef, $two) = @array;  # better written `my $two = $array[2];`

my ($one, $two) = @array[1, 2];    # note that 'array' is prefixed with a @
my ($one, $two) = @array[1 .. 2];  # indicating that you are requesting a list
                                   # in turn, the [subscript] sees list context
my @slice = @array[$start .. $stop];  # which lets you select ranges

将args解压缩到子程序:

my ($first, $second, @rest) = @_;

采用name => value对的方法:

my ($self, %pairs) = @_;

答案 1 :(得分:0)

您可以通过在列表上下文中使用m//运算符来获取匹配的子表达式列表,例如通过将其返回值分配给变量列表(就像您当前对子例程调用一样)。因此,您可以使用更简单的构造替换子例程:

my $str = shift @dataRecord;
my ($test1_name, $test2_name, $test3_name) =
    $str =~ m/^test1 (.*), test2 (.*), test3 (.)/;

或者,如果要对for数组的每个元素执行此操作,请@dataRecord循环:

for my $str (@dataRecord) {
    my ($test1_name, $test2_name, $test3_name) =
        $str =~ m/^test1 (.*), test2 (.*), test3 (.)/;
}