Understanding scalers and variables in Perl

Home > Search

In Perl, a scaler is synonymous with a variable. Regardless if you use the label scaler or variable, you are probably referencing the same thing. A scaler/variable is identified by the $ character, and the scaler/variable contains data, such as an integer (numbers), text, special characters, or even an entire file. In this example, $foo is the scaler the text "Hello World" would be the data in the scaler/variable.

One of the nice things about Perl is that unlike some other languages, such as Java, you do not need to specify the scaler/variable type. For example, in Java, when creating a variable in Java, you would need to specify the variable as an int (integer). You do not need to worry about this in Perl, which is nice.

my $foo = "Hello World";


Variables can be printed using the print operator.

print $foo;


In this example, print $foo; will produce the following result.

Hello World


Variables in a string

Let's consider an example where you need to print a variable in a string.

print aaa$foobbb;


The above example will produce only aaa, since the variable will be interpreted as $foobbb. To resolve this, use curly braces.

print aaa${foo}bbb;


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.