How should I compare Perl references?

后端 未结 3 699
孤独总比滥情好
孤独总比滥情好 2021-02-11 18:32

I want to check if two references point to the same object. It seems I can simply use

if ($ref1 == $ref2) { 
 # cheap numeric compare of references
 print \"ref         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-11 19:09

    The function you are looking for is refaddr from Scalar::Util (after ensuring that the values being compared really are references):

    use Scalar::Util 'refaddr';
    
    if ($obj1 and ref($obj1) and $obj2 and ref($obj2) and
        refaddr($obj1) == refaddr($obj2))
    {
        # objects are the same...
    }
    

提交回复
热议问题