Scalar::Util
Scalar::Util offers small checks such as whether a value is a number, an object or a reference.
In this page:
Scalar::Util
looks_like_number tells you whether a string would be treated as a number by Perl, which is safer than guessing with a regular expression. blessed returns the class name of an object or undef for anything else, and reftype returns the underlying type of a reference even when it is blessed. weaken turns a reference into a weak one that does not keep its target alive, which is used to break reference cycles.
Note:
blessed($x) is the safe way to check that a value is an object before calling methods on it.
Example: Scalar::Util
use strict;
use warnings;
use Scalar::Util qw(looks_like_number blessed reftype weaken);
for my $v ("42", "3.14", "1e5", "abc", "", "0x10") {
printf "%-6s %s\n", "'$v'", looks_like_number($v) ? "number" : "not a number";
}
my $obj = bless { id => 1 }, 'Widget';
print "blessed: ", blessed($obj), "\n";
print "blessed of plain hashref: ", defined blessed({}) ? "class" : "undef", "\n";
print "ref: ", ref($obj), " reftype: ", reftype($obj), "\n";
my $parent = { name => "parent" };
my $child = { name => "child", parent => $parent };
$parent->{child} = $child;
weaken($child->{parent});
print "child's parent: $child->{parent}{name}\n";
# Output:
# '42' number
# '3.14' number
# '1e5' number
# 'abc' not a number
# '' not a number
# '0x10' not a number
# blessed: Widget
# blessed of plain hashref: undef
# ref: Widget reftype: HASH
# child's parent: parent
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using ref to detect objects when the reference might be a plain one
- Forgetting that looks_like_number accepts values like 1e5 and 0 but not hex strings like 0x10
- Creating circular references without weakening one side
Chapter Summary
- looks_like_number validates numeric strings
- blessed returns the class of an object
- reftype ignores blessing
- weaken breaks reference cycles
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: