← Back to Perl Course | Chapter 8: Modules | Lesson 4 of 7

Scalar::Util

Scalar::Util offers small checks such as whether a value is a number, an object or a reference.

In this page:

  1. Scalar::Util

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

perl
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
Common Mistakes
  1. Using ref to detect objects when the reference might be a plain one
  2. Forgetting that looks_like_number accepts values like 1e5 and 0 but not hex strings like 0x10
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.