ALL ABOUT VARIABLES


In this post we will learn about scalar variables and various conventions of naming variables.

A variable is a storage container which stores values either provided by user or maybe hardcoded by programmer in a script. These variables stores values temporarily in memory for further operation or for whatsoever purpose.

We can store anything in SCALAR variable, like numbers or strings. Perl itself converts the data to its data type in memory. Unlike C language, we do not have to explicitly define a variable as int, char, float, etc. In perl anytime we want to store any value, we just have to assign the value to variable and leave the rest on perl interpreter to decide what kind of data we entered, we need not be bothered about it.

RULES FOR NAMING VARIABLES

1. If "use strict" is used in our script, we must define our variables using the function "my"
    Ex: my $variablename;

2. A variable name must start with a '$' symbol.

3. A variable name may contain alphanumeric characters and underscores.

4. The first character in the variable name after the '$' symbol must be a letter.

5. A variable name must be upto 255 characters.

6. Variable Names must be case sensitive, ie. $ABC not equal to $abc.

7. A Variable Name cannot start with a Number.

A SCALAR variable used with double quotes will interpolate to the value of the variable.

With that said, lets check this small perl script.

#!/usr/bin/perl

use strict;
use warnings;


my $arg1 = "Computer Korner";
my $arg2 = " is a great group.\n";
my $arg3 = " members are awesome.";

print "$arg1 $arg2";

print "${arg1}'s $arg3";


We notice that in the second print statement, the variable name arg3 is enclosed within curly braces, this is necessary because we have a single quote after the variable name in the second print statement, and to keep perl out of any confusion we place the variable name within curly braces.

Note: This is due to the fact that certain ASCII characters within double quotes have special meanings.

An interesting situation:

What if we declare a variable and we don't assign a value to it and try to print the variable?
This will create an error, as an unassigned variable when printed or used has a value as "undefined".

Example:


#!/usr/bin/perl

use strict;
use warnings;

my $name;
print "$name";

The above will produce an error.


That's all for this part, hope it was interesting.

Feel free to comment for any doubts.
Feel Free To Leave A Comment
If Our Article has Helped You, Support Us By Making A Small Contribution, Thank You!

1 comment:

  1. use strict;
    use warning;

    $a=10;
    $b=10
    print "a=$a and b=$b\n";

    When I run this code it does not throw an error. However when i replace $b with $tar, it throws an error. "global symbol requires explicit package name". Can you tell me why a single char variable name is not an issue? I am running it on windows workstation.

    ReplyDelete