How to determine if an object or link has a valid string enforcement?

I came across a situation (when registering various data changes) where I need to determine if the link has the correct string enforcement (for example, it can be correctly printed in the log or saved in the database). There is nothing in Scalar :: Util for me to do something using other methods in this library:

use strict; use warnings; use Scalar::Util qw(reftype refaddr); sub has_string_coercion { my $value = shift; my $as_string = "$value"; my $ref = ref $value; my $reftype = reftype $value; my $refaddr = sprintf "0x%x", refaddr $value; if ($ref eq $reftype) { # base-type references stringify as REF(0xADDR) return $as_string !~ /^${ref}\(${refaddr}\)$/; } else { # blessed objects stringify as REF=REFTYPE(0xADDR) return $as_string !~ /^${ref}=${reftype}\(${refaddr}\)$/; } } # Example: use DateTime; my $ref1 = DateTime->now; my $ref2 = \'foo'; print "DateTime has coercion: " . has_string_coercion($ref1) . "\n\n"; print "scalar ref has coercion: " . has_string_coercion($ref2) . "\n"; 

However, I suspect that there may be a better way to determine this by checking the gut of this variable. How can this be done better?

+6
reference perl coercion
source share
1 answer

From perldoc overload :

overload::StrVal(arg)

Gives a string value of arg , as in the case of no overload.

 sub can_stringify { my ($obj) = @_; return "$obj" ne overload::StrVal($obj); } 

Note that overload::Method is not suitable here because :

  • 'bool' , '""' , '0+' ,

If one or two of these operations are not overloaded, the rest can be used.

Therefore, checking only when overloading '""' will lead to the return of false negatives compared to the method that you indicate in your question.

+6
source share

All Articles