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, =.
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?
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"