所以我正在学习Perl并进入关于哈希的章节.我明白’=>’ operator是逗号运算符的别名.但是当我尝试制作一个值undef时,我得到了警告
在连接(.)中使用未初始化的值$last_name {“dino”}或在./learning.pl第18行使用字符串.
在连接(.)中使用未初始化的值$last_name {“dino”}或在./learning.pl第18行使用字符串.
use warnings; use strict; my %last_name = ( fred => 'flintston',dino => undef,barney => 'rubble',betty => 'rubble',); my $key; my $value; if(%last_name) { foreach $key (sort keys %last_name) { print("$key => $last_name{$key}\n"); } }
但是当我将哈希线更改为:
my %last_name = ( fred => 'flintston',dino => undef => barney => 'rubble',);
它工作正常,并返回值为undef.我所做的只是替换使用’=>’分隔键/值的逗号运算符操作符.
如果两个运算符应该是相同的,为什么后面的工作而不是前者?
解决方法
它们并不完全相同. “胖逗号”还做了一件事:当它是一个单词时,它会引用左侧操作数.因此,
undef,1
相当于
undef(),1
而
undef => 1
相当于
'undef',1
见perlop:
The => operator is a synonym for the comma except that it causes a word on its left to be interpreted as a string if it begins with a letter or underscore and is composed only of letters,digits and underscores.