How to check if a Perl scalar supports a link to a specific routine?

In other words, how can I check for equality in coderef?

The smartmatch operator does not work for obvious reasons (it will be considered CODE->(ANY) ), but I included it in the example to show what I need:

 use strict; use warnings; use feature 'say'; sub pick_at_random { my %table = @_; return ( values %table )[ rand( keys %table ) ]; } my %lookup = ( A => \&foo, B => \&bar, C => \&baz ); my $selected = pick_at_random( %lookup ); say $selected ~~ \&foo ? "Got 'foo'" : $selected ~~ \&bar ? "Got 'bar'" : $selected ~~ \&baz ? "Got 'baz'" : "Got nadda" ; 
+8
perl
source share
1 answer

You can use normal (numerical) equality ( == ), as is the case with all references:

 Perl> $selected == \&foo Perl> $selected == \&bar Perl> $selected == \&baz 1 

Live in action here

This breaks when the link is blessed with something that overloads == or 0+ (which is unlikely for coderefs). In this case, you would compare Scalar::Util::refaddr($selected) .

From man perlref :

Using a reference as a number creates an integer representing its storage location in memory. The only useful thing to do with this is to compare two reference numeric data to see if it refers to the same location.

  if ($ref1 == $ref2) { # cheap numeric compare of references print "refs 1 and 2 refer to the same thing\n"; } 
+11
source share

All Articles