Perl Programming Page 3 - Scalars and Variables |
Now it is time to talk about variables. As explained earlier, a variable is storage for your scalars. Once you’ve calculated 42*7, it’s gone. If you want to know what it was, you must do the calculation again. Instead of being able to use the result as a halfway point in more complicated calculations, you’ve got to spell it all out in full. That’s no fun. What we need to be able to do, and what variables allow us to do, is store a scalar away and refer to it again later. A scalar variable name starts with a dollar sign, for example:$name. Scalar variables can hold either numbers or strings, and are only limited by the size of your computer’s memory. To put data into our scalar, we assign the data to it with the assignment operator=. (Incidentally, this is why numeric comparison is==, because= was taken to mean the assignment operator.) What we’re going to do here is tell Perl that our scalar contains the string"fred". Now we can get at that data by simply using the variable’s name: #!/usr/bin/perl -w $name = "fred"; Lo and behold, our computer announces to us that $ perl vars1.pl Now we have somewhere to store our data, and some way to get it back again. The next logical step is to be able to change it. Modifying a Variable Modifying the contents of a variable is easy, just assign something different to it. We can say #!/usr/bin/perl -w $name = "fred"; And watch our computer have an identity crisis: $ perl vars2.pl We can also do a calculation in several stages: #!/usr/bin/perl -w $a = 6 * 9; This code prints $ perl vars3.pl While this works perfectly fine, it’s often easier to stick with one variable and modify its value, if you don’t need to know the stages you went through at the end: #!/usr/bin/perl -w $a = 6 * 9; The assignment operator =, has very low precedence. This means that Perl will do the calculations on the right-hand side of it, including fetching the current value, before assigning the new value. To illustrate this, take a look at the sixth line of our example. Perl takes the current value of $a, adds three to it, and then stores it back in $a.
blog comments powered by Disqus |
|
|
|
|
|
|
|