Updated: 11/12/2023 by Computer Hope
Variable and value

A variable is a named unit of data that is assigned a value. If the value is modified, the name does not change. Variables are used with most programming languages and come in many forms, defined by the script or software programmer.

Some variables are mutable, meaning their values can change. Other variables are immutable, meaning their value, once assigned, cannot be deleted or altered.

If a variable's value must conform to a specific data type, it is called a typed variable.

Example of a variable

Below is an example of a variable in the Perl programming language.

my $fullname = "Computer Hope";
print "There is hope, $fullname";

In the example above, the variable, named fullname, is declared using the Perl keyword my. In Perl, the dollar sign $ indicates that fullname is the name of a variable, but the dollar sign is not part of the variable name.

In the first line of the program, the variable is assigned a value using the assignment operator, = (equal).

The value of fullname is the string Computer Hope, which is enclosed in double quotes. The double quotes indicate that the text inside is a string, but are not part of the string data.

When you run the program, the print statement replaces the variable name, $name, with its string value. Then, it displays the result:

There is hope, Computer Hope

What is a global variable?

In most programming languages, a global variable is declared outside a class, routine, or subroutine. Global variables are available for use throughout a script or program code, and can store and pass values from one class, routine, or subroutine to another.

A global variable is often declared at or near the beginning of the script or program code.

What is a private variable?

In object oriented programming, a private variable is declared in an object class. Its value cannot be accessed or modified by code outside the lexical scope of that class.

Changing a variable

There are many different ways a variable can be deleted, changed, exchanged, or set as a different value. Below are examples of how a variable could be changed, with comments explaining what's being done.

my $x = "Computer";	#Declares x as "Computer"
my $y = "hope"; #Declares y as "hope"
print "$x"; #Prints "Computer"
$y = ucfirst($y); #Uppercases first letter of $y
print "$y"; #Prints "Hope"
$x = "$x $y"; #Sets x as "Computer Hope"
print "$x"; #Prints "Computer Hope"
$y = ""; #Set (erase) y variable to null print "$y"; #Prints nothing $y = $x; #Set y variable to x value
print "$y"; #Prints "Computer Hope"

%1, Constant, Dependent variable, Environment variable, Literal, Metasyntactic variable, Programming terms, Routine and subroutine, X