Perl Programming Perl 101 (Part 2) - Of Variables And Operators |
In the first part of this tutorial, we introduced you to the basics of Perl, Austin Powers-style. This week, we're going to get down and dirty with variables and operators, and also provide you with a brief introduction to Perl's conditional expressions. To begin with, let's answer a very basic question for all those of you unfamiliar with programming jargon: what's a variable when it's at home? A variable is the fundamental building block of any programming languages. Think of a variable as a container which can be used to store data; this data is used in different places in your Perl program. A variable can store both numeric and non-numeric data, and the contents of a variable can be altered during program execution. Finally, variables can be compared with each other, and you - the programmer - can write program code that performs specific actions on the basis of this comparison. Every language has different types of variables - however, for the moment, we're going to concentrate on the simplest type, referred to in Perl as "scalar variables". A scalar variable can hold any type of value - integer, text string, floating-point number - and is usually preceded by a dollar sign. The manner in which scalar variables are assigned values should be clear from the following example: #!/usr/bin/perl
# a simple scalar variable
$name = "mud";
# and an example of how to use it
print ("My name is ", $name);And here's what the output of that program looks like: My name is mud Really?! We feel for you... It shouldn't be too hard to see what happened here - the scalar variable $name was assigned the text value "mud", and this value was then printed to the console via the print() statement. Although assigning values to a scalar variable is extremely simple - as you've just seen - there are a few things that you should keep in mind here:
#!/usr/bin/perl # declare a variable $number = 19; print ($number, " times 1 is ", $number,"\n"); print ($number, " times 2 is ", $number * 2, "\n"); print ($number, " times 3 is ", $number * 3, "\n"); print ($number, " times 4 is ", $number * 4, "\n"); print ($number, " times 5 is ", $number * 5, "\n"); And here's what the output looks like: 19 times 1 is 19 19 times 2 is 38 19 times 3 is 57 19 times 4 is 76 19 times 5 is 95
blog comments powered by Disqus |