Variables, boxes of information
Most programs contain information that is repeated multiple times. It could be a name, such as Jack, or a number such as 3. It is not unusual to have to change that information across the entire program. In such a situation, variables comes in handy. Variables are just like boxes that contain information. To find out what is stored in the box, you just look inside.
In the first example, we write another version of our hello world program. The only difference is that we now exchange "Hello" and "World" with variables.
#!/usr/bin/perl use strict; my ($noun, $formulaic); $noun = "World"; $formulaic = "Hello"; print "$formulaic, $noun!\n"; print "$noun, $formulaic!\n";
The line that starts with my, is a line that declares variables. Every variable has to be declared. This is a good thing, in case you would misspell a variable name, the interpretter will give you an error. The lines that follow assigns values to the variables. This is like putting a paper with information inside your box.
#!/usr/bin/perl use strict; my ($noun, $formulaic); $noun = "Yellowbrick road"; $formulaic = "Goodbye"; print "$formulaic, $noun!\n"; print "$noun, $formulaic!\n";
The only thing that changed between the first and second example, is the value that was assigned to the variables. The print lines were the same in both examples. In the first example formulaic contained "Hello" and noun contained "World". This meant that the output of the prints were: "Hello, World!" and "World, Hello!". In the second examples formulaic contained "Goodbye" and noun contained "Yellowbrick road". So in the second example, the outputs would become: "Goodbye, Yellowbrick road!" and "Yellowbrick road, Goodbye!".
#!/usr/bin/perl use strict; my ($value_a, $value_b, $sum); $value_a = 13; $value_b = 25; $sum = $value_a + $value_b; print "A = $value_a, B = $value_b and the sum is $sum\n";
In our final examples, we have done a couple of things differently. The first notable thing we have done, is to assign numbers to our variables instead of text. The text was surrounded by quotation marks, but the numbers are not. This is a way to distinguish numbers from text. The second notable difference is that sum is assigned a value, by calculating the sum of value_a and value_b. The final output would be: "A = 13, B = 25 and the sum is 38". This shows another possible usage of variables, the ability to calulate values, that are unknown when writing the program. This is a very important concept in programming.