Learning XS - What is in my variable

Over the past year, I’ve been self-studying XS and have now decided to share my learning journey through a series of blog posts. This second post introduces the fundamentals of type checking variables in XS.

What is a variable in Perl?

In Perl, a variable is a named storage location that holds a value you can use and manipulate in your program. Perl fundamentally has three types of variables which are:

  1. Scalars ($) hold single values (numbers, strings, references)
  2. Arrays (@) hold ordered lists of scalars
  3. Hashes (%) hold key-value pairs

It's important to understand that arrays always store lists, and hashes always store key-value pairs. Scalars, on the other hand, are more flexible they can hold various types of data, including numbers, strings, or references. This flexibility is why Perl provides the ref keyword, which allows you to determine the basic type of a scalar reference. However, if you need to identify the actual underlying type of a scalar reference including those that have been blessed you'll need to use Scalar::Util and its reftype function, which handles these cases more transparently.

How does this translate to XS?

In Perl, all data regardless of its type is ultimately passed to XS as an 'SV' (scalar value pointer). Arrays and hashes are actually special types of scalars that reference array or hash structures. Internally, they also have their own specific types: 'AV' for arrays and 'HV*' for hashes. The Perl C API offers several functions for validating an 'SV'. Some of the commonly used ones include:

  1. SvOK(sv): True if sv contains a defined value.
  2. SvROK(sv): True if sv is a reference.
  3. SvTYPE(sv): Returns the internal type of the SV.
  4. SvRV(sv): Dereferences an SV reference to get the underlying value.

SvTYPE is an important function in Perl’s C API that returns the internal type of a Perl scalar value (SV*). It tells you what kind of data structure the SV currently holds, which is essential for type checking in XS. Below is a reference table to what you can check SvTYPE against.

Screenshot 2025-05-31 at 15.45.44.png

Due to limitations with the markdown rendering code on blogs.perl.org, I haven’t published the remainder of this article here.If you’d like to continue reading, the full version is available on dev.to: https://dev.to/lnation/learning-xs-what-is-in-my-variable-nfm

Leave a comment

About Robert Acock

user-pic I blog about Perl.