Perl:如何访问外部文本文件中哈希数组引用变量的键对应值
Got it, let's break this down for you. You're totally right about the issue— that $basket from the external text is an array reference, not a regular array or hash. So trying to access it with $basket[0]{'Apple'} throws an error because Perl treats $basket as a regular array name, but it's actually a scalar holding a reference to an array in memory.
To get the value tied to the 'Apple' key, you need to handle the reference properly. Here are two straightforward ways to do this:
方法1:使用箭头符号(推荐写法)
This is the most common and readable way to work with references in Perl. The -> operator lets you traverse the reference hierarchy directly:
$basket = [ { 'Apple' => 'red', 'Banana' => 'yellow', 'Grapes' => 'purple' }, ]; print $basket->[0]{'Apple'} . "\n"; # 输出red
方法2:显式解引用数组引用
If you prefer more explicit syntax, you can use @{} to convert the array reference into a regular array before accessing its elements:
$basket = [ { 'Apple' => 'red', 'Banana' => 'yellow', 'Grapes' => 'purple' }, ]; print @{ $basket }[0]{'Apple'} . "\n"; # 同样输出red
To contrast with your working code:
- Your
%fruitsis a regular hash variable, so$fruits{'Apple'}works directly - The external
$basketis an array reference where the first element is a hash— you have to first target that array element (via de-referencing or the arrow) before accessing the hash key
A quick side note: If you're dynamically reading and executing code from external files, make sure you're handling it safely to avoid injection risks. But for just accessing the key-value pair, either of the above methods will fix your problem.
内容的提问来源于stack exchange,提问作者Sheograph

