perl - 如何仅切片定义的值?

标签 perl perl-data-structures

我可以将 kes/values 切片如下:

$item->%{ @cols }
但是如果在 $item 处不存在某些列它将在生成的哈希中创建。
我可以只切片定义的值吗?

最佳答案

您可以检查它们是否存在。

$item->%{ grep {exists $item->{$_}} @cols }
应该只对现有值进行切片。
无论如何 - 简单地访问这些值不应该自动激活它们。只有当您将这些值作为参数传递给某个函数并且它们在那里隐式别名时,它们才会自动激活。
use strict;
use warnings;
use Data::Dumper;

my @cols =qw (a b c);
my $item = [{a => 1, c => 3}];

print Dumper({$item->[0]->%{ grep {exists $item->[0]->{$_}} @cols }});
print Dumper($item);

print Dumper({$item->[0]->%{ @cols }});
print Dumper($item);

print Dumper($item->[0]->%{ grep {exists $item->[0]->{$_}} @cols });
print Dumper($item);

print Dumper($item->[0]->%{ @cols }); ## Only here does autovivication take place
print Dumper($item);
只有最后一次打印将生成:
$VAR1 = [
          {
            'c' => 3,
            'a' => 1,
            'b' => undef
          }
        ];
表明 b 被自动激活。

关于perl - 如何仅切片定义的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67602931/

相关文章:

珀尔 :Out of Memory Error while building a 2d array at run time

perl - Perl 中的 BigQuery : append query data to table

perl - 使用数组寻址哈希的哈希

perl:打开文件句柄,写入其中,稍后给它命名?

linux - 如何格式化程序集注释

perl - 如何访问该数据结构中的元素?

arrays - Perl 数组引用和避免 "Type of arg 1 to keys must be hash"错误

arrays - 如何循环进入数组哈希值的哈希值?

html - 使用 Perl CGI 的复选框

perl:在第 N 个位置写入文件