DEV Community

Cover image for Learning Perl - Scalars
LNATION for LNATION

Posted on • Edited on

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.

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.