在Perl中,我一直对如何从数组条目中干净地分配多个局部变量感到困惑.
我总是在subs中使用以下语法,所以我对它有些熟悉:
my ($var1, $var2) = @_
Run Code Online (Sandbox Code Playgroud)
但其他的变化让我感到困惑.例如,我有以下代码可行:
for my $ctr (0 .. $#matchingLines) {
my $lineNo = $matchingLines[$ctr][0];
my $text = $matchingLines[$ctr][1];
Run Code Online (Sandbox Code Playgroud)
其中" @matchingLines"是两元素数组的数组.
我希望我能将最后两行转换为显而易见的:
my ($lineNo, $text) = $matchingLines[$ctr];
Run Code Online (Sandbox Code Playgroud)
那当然不行.我尝试了很多变化,但我发现任何有效的东西.
只需取消引用数组ref:
my ( $lineNo, $text ) = @{ $matchingLines[$ctr] };
Run Code Online (Sandbox Code Playgroud)
有关其他示例,请查看Perl Data Structures Cookbook.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |