[英]what's the best way to get multiple values from a perl array?
例如,
首先,我將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);
}
我有更好的方法來完成這項任務嗎?
您可以將操作鏈接在一起,同時減少所需的語法。 這樣做的好處是可以在減少語法噪聲的同時強調程序的重要部分。
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) = @_;
您可以通過在列表上下文中使用m//
運算符來獲取匹配的子表達式列表,例如通過將其返回值分配給變量列表(就像您當前對子例程調用一樣)。 因此,您可以使用更簡單的構造替換子例程:
my $str = shift @dataRecord;
my ($test1_name, $test2_name, $test3_name) =
$str =~ m/^test1 (.*), test2 (.*), test3 (.)/;
或者,如果要對@dataRecord
數組的每個元素執行此操作,則為for
循環:
for my $str (@dataRecord) {
my ($test1_name, $test2_name, $test3_name) =
$str =~ m/^test1 (.*), test2 (.*), test3 (.)/;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.