Perl Programming/Scalar variables

< Perl Programming

Scalar Variables

Introduction to Scalar 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/perl
 
 use warnings;
 
 $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.

Assigning and Using Scalar Variables

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. A scalar variable holds a single value.

Naming Conventions

Using Scalar Variables

Scalar Variables and Strings

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/perl
 
 use warnings;
 
 $variable = 4;
 print "I saw $variable lions!";

Would return "I saw 4 lions!"

 #/usr/bin/perl
 
 use warnings;
 
 $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.

Comparison Operators

Main article: Perl Programming/Operators

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.

Numeric Comparison Operators

Here is the list of numeric comparison operators:

String Comparison Operators

Here is the list of string comparison operators:

Note
The two 'Comparison' operators <=> and cmp are 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.

Exercises

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.