Perl – Hash和=>运算符

前端之家收集整理的这篇文章主要介绍了Perl – Hash和=>运算符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我正在学习Perl并进入关于哈希的章节.我明白’=>’ operator是逗号运算符的别名.但是当我尝试制作一个值undef时,我得到了警告
在连接(.)中使用未初始化的值$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.

猜你在找的Perl相关文章