Handling missing references

后端 未结 2 1600
深忆病人
深忆病人 2021-01-24 12:23

I\'m getting the error Can\'t use an undefined value as an ARRAY reference in a Perl script. Below is a highly simplified version.

Basically I have setup a

2条回答
  •  长发绾君心
    2021-01-24 12:49

    $data_for{B} is not defined, so the attempt to dereference it as an array (in the sort @{$data_for{$letter}} expression) is an error.

    One workaround is to assign a (empty) value for $data_for{B}:

    $data_for{'A'} = ['apple', 'astronaut', 'acorn'];
    $data_for{'B'} = [];
    $data_for{'C'} = ['car', 'cook', 'candy'];
    

    but a more general workaround is to use the '||' operator (or '//' operator for Perl >=v5.10) to specify a default value when a hash value is not defined

    foreach my $item ( sort @{$data_for{$letter} || []}) { ... }
    

    When $data_for{$letter} is undefined (and therefore evaluates to false), the expression $data_for{$letter} || [] evaluates to a reference to an empty array, and the array dereference operation will succeed.

提交回复
热议问题