A Wikibookian suggests that this book or chapter bemerged withPerl Programming/Basic Variables. Please discuss whether or not this merger should happen on thediscussion page. |
| Previous: Data types | Index | Next: Array variables |
Now that you understand how to use strings and numbers in Perl, you need to start learning how to use variables.The best way to learn about scalar variables - Perl talk for a single variable, as against a group or list of values - is to look at an example.
#!/usr/bin/perlusewarnings;$my_scalar_variable="Hello, Sir!\n";print$my_scalar_variable;
Now let's break this program down:
| Try it! Type in the program mentioned above and run it. |
In the course of writing a program, you will most likely use a variable. What is a variable? A variable is something that stores data. Ascalar variable holds a single value.
You may recall that earlier in the book, I said that whether you use" or' in strings makes a big difference in the interaction of strings and variables. Well now I am going to explain what I meant.
Now that you know what a variable is, what if you wanted to put a variable in a string? Here's the difference:
#/usr/bin/perlusewarnings;$variable=4;print"I saw $variable lions!";
Would return "I saw 4 lions!"
#/usr/bin/perlusewarnings;$variable=4;print'I saw $variable lions!';
Would return "I saw $variable lions!"
| Try it! Type in the programs mentioned above and run them. |
This effect is because of what I said before,single quoted strings are interpreted literally.
There are operators that are used for comparing numbers and strings. This can be very useful when you get to more advanced programming. Both numbers and strings have their own set of operators which test for a condition such as equal or not equal and return either true or false.
Here is the list of numeric comparison operators:
Here is the list of string comparison operators:
| Note The two 'Comparison' operators<=>andcmpare slightly different from the rest. Rather than returning only true or false, these operators return 1 if the left argument is greater than the right argument, 0 if they are equal, and -1 if the right argument is greater than the left argument. |
| Previous: Data types | Index | Next: Array variables |