Learning Perl - Scalars


Learning Perl - Scalars


Before moving onto more complex topics lets come back to how we represent data in Perl. The most common data type in Perl is what we call a scalar, which is a representation of a single value. Scalars can be numbers, strings, or references to other data structures. This means that your scalar variable can contain a 'single thing', but that 'thing' can be 'anything' at any given moment based upon what you assign to it.

Based upon that perl offers you a variety of ways to create and manipulate scalars and based upon the type of scalar you are using you can do different things with it.

The main type of scalars in Perl are:

Type Description
Number Integer or floating-point value.
String Sequence of characters, can be single or double quoted.
Reference Scalar that refers to another variable (array, hash, subroutine, etc.).
Undefined A scalar with no value assigned, represented by undef.
Regular Expr A compiled regular expression, created with qr//, stored as a scalar.
Glob A typeglob, which can be used as a scalar to refer to an entire symbol table entry (e.g. *FOO).
Object A blessed reference, used for object-oriented programming.
Code A scalar containing Perl subroutine.

Each of these scalar types has its own set of operations and behaviours. For example, you can perform arithmetic operations on numbers, string concatenation on strings, and dereferencing on references. Objects can be manipulated using methods defined in their classes, but we will cover Objects over a series of posts later in this series, we have not even got to subroutines yet. The following table will give you an overview of what you can do with a scalar.

Operation Example Description
Assignment $x = 42; Assigns a value to a scalar variable.
Addition/Subtraction $x + $y, $x - $y Adds or subtracts numeric scalars.
Multiplication/Division $x * $y, $x / $y Multiplies or divides numeric scalars.
String Concatenation $a . $b Joins two strings together.
String Repetition $a x 3 Repeats a string a given number of times.
String Interpolation "Hello $name" Embeds scalar values inside double-quoted strings.
Comparison (Numeric) $x == $y, $x < $y Compares numeric scalars.
Comparison (String) $a eq $b, $a lt $b Compares string scalars.
Defined Check defined($x) Checks if a scalar has a value other than undef.
Undefine undef $x; Removes the value from a scalar, making it undefined.
Reference Dereference $$ref, @$ref, %$ref Accesses the value referred to by a reference scalar.
Method Call (Object) $obj->method() Calls a method on an object (blessed reference).

If you do not know the type of scalar you are dealing with because that variable is dynamically assigned then perl provides a way to check the type of scalar you are dealing with using the 'ref' keyword. This keyword returns the type of reference if the scalar is a reference, or an empty string if it is not, when it return empty it means you have either a string or a number, to validate further you have either a string or a number then a regex must be used or the Scalar::Util module looks_like_number function.

Today we are going to just demonstrate the basic operations on scalars, and how to create them. Create a new file 'scalars.pl' and add the following code to it:

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use Scalar::Util qw(looks_like_number);
# Creating Scalars
my $number = 42;                # Numeric scalar
my $string = "Hello, World!";  # String scalar
my $ref = \$number;             # Reference to a scalar
my $array_ref = [1, 2, 3];      # Reference to an array
my $hash_ref = { key => 'value' }; # Reference to a hash
my $undef_scalar;              # Undefined scalar

# Operations on Scalars
say "Number: $number";
say "String: $string";
say "Reference to number: $$ref";  # Dereferencing
say "Array reference: @$array_ref";  # Dereferencing array reference
say "Hash reference: $hash_ref->{key}";  # Dereferencing hash reference
say "Undefined scalar: ", defined($undef_scalar) ? $undef_scalar : 'undef';

for my $check ($number, $string) {
    # Check if a scalar looks like a number
    if (looks_like_number($check)) {
        say "$check looks like a number.";
    } else {
        say "$check does not look like a number.";
    }
}

for my $check ($string, $ref, $array_ref, $hash_ref) {
    if (ref($check)) {
        say "The scalar is a reference of type: ", ref($check);
    } else {
        say "The scalar is not a reference.";
    }
}
Enter fullscreen mode Exit fullscreen mode

Now you can run this script using the command:

perl scalars.pl
Enter fullscreen mode Exit fullscreen mode

You should see the following output:

Number: 42
String: Hello, World!
Reference to number: 42
Array reference: 1 2 3
Hash reference: value
Undefined scalar: undef
42 looks like a number.
Hello, World! does not look like a number.
The scalar is not a reference.
The scalar is a reference of type: SCALAR
The scalar is a reference of type: ARRAY
The scalar is a reference of type: HASH
Enter fullscreen mode Exit fullscreen mode

This output demonstrates the creation and manipulation of different scalar types in Perl, including numeric scalars, string scalars, references to scalars, arrays, and hashes. It also shows how to check if a scalar looks like a number and how to determine the type of reference a scalar holds.

It's important to understand the type of scalar you are dealing with, as it will affect how you can manipulate and use that scalar in your Perl programs. If you do try to perform an operation on a scalar that is not valid for its type, Perl will throw an error or warning, which is why it's essential to be aware of the type of scalar you are working with.

In the next post we will cover references and how to build nested data structures in more detail.

Related Blogs

Learning Perl – Introduction
Perl has long been known as the “duct tape of the Internet,” or "the Swiss Army chainsaw of scripting...
Learning Perl - Variables
I will attempt to explain things in this post in a way that is easy to understand, even for those who...
Learning Perl - Arrays
As stated in the previous post, Perl has three types of variables: scalars, arrays and hashes. Today...
Learning Perl - Hashes
In the last post we covered the basics of arrays, today we will look at hashes in more detail. What...
Learning Perl - Conditional Statements
So far we have covered basic variables in Perl, today we are going to look at how to use these...
Learning Perl - Loops and Iteration
In previous posts, we explored variables, arrays, hashes, and conditional statements in Perl. Now...
Learning Perl - References
In the last post we learnt how to create a reference to a scalar, an array, and a hash. In this post,...
Learning Perl - Ternary Operators
In a previous post, we learned about conditional statements in Perl. The ternary operator is an...
Learning Perl - Subroutines
Subroutines are one of the most important building blocks in programming. They allow you to organise...
Learning Perl - Regular Expressions
Regular expressions also known as regex or regexp, are a powerful way to match patterns in text. Most...
Learning Perl - Modules
A module in Perl is a reusable piece of code that can be included in your scripts to provide...
Learning Perl - CPAN
In the last post I showed you how to create a new module and how to use it in your code. In this post...
Learning Perl - Plain Old Documentation
When you write and program in any language it is good practice to document your code. Each language...
Learning Perl - Testing
In this post we will look at how to test Perl code using the Test::More module. Like documentation,...
Learning Perl - Exporting
In programming, we often want to share functionality across different parts of our code. In Perl,...
Learning Perl - Object Orientation
Object-Oriented Programming (OOP) is a widely used programming paradigm that enables the creation of...
Learning Perl - Inheritance
In the last post we discussed Object Oriented Programming in Perl, focusing on the basics of creating...
Learning Perl - File Handles
In programming file processing is a key skill to master. Files are essential for storing data,...
Learning Perl - Prototypes
Today we are going to discuss Perl subroutine prototypes, which are a way to enforce a certain...
Learning Perl - Overloading Operators
In the last post we investigated prototype subroutines in Perl. In this post, we will look at...