简体   繁体   中英

Why Scalar::Util::reftype return `undef` instead of empty string?

ref returns empty string for scalar values.

Why Scalar::Util::reftype return undef instead of empty string like ref does?

What is the benefit of undef ? In compare, the benefit of empty string is less coding while doing:

reftype $data eq 'HASH'

When undef is returned we will get Use of uninitialized value while eq at ... and we should do:

(reftype($data) //'') eq 'HASH'

Generally speaking, bad input results in undef (if not an exception), which (eventually) results in a warning so that the error can be found.

The most controversial warning is the uninitialized warning because there's no immediate benefit. But when one considers it part of the larger error framework, one realizes it's a key component of Perl's error detection and debugging system. Having functions return undef on bad input is another component of that system.

I dispute your claim that it makes code smaller. For starters, one should never use reftype as it breaks Perl's data model. (This is why keys $ref was always a bad idea, and never went past the experimental stage.) This means the amount of code in question is quite small.

Still, it can make sense to produce data that requires its use, as long as certain limits are guaranteed. (For example, the output of decode_json can requires it's use, and it can be used safely because decode_json will never produce objects or magical variables.) When it is needed, a number of checks are usually performed, so returning an empty string doesn't really help.

my $type = reftype($val);
if (!defined($type)) { ... }
elsif ($type eq 'HASH') { ... }
elsif ($type eq 'ARRAY') { ... }
...

Note that changing reftype would breaks this code, so changing reftype is not an option. I was going to say you could ask the author for an alternate sub that behaves the way you want, but you could just as easily produce that sub yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM