Perl Notes: Variables
PERL is Practical Extraction and Report Language and is best used for data manipulations and operations. Here we take a look a some of it's Variables
Variables in Perl must begin with aA_ (i.e lower case alpha,upper case alpha or an underscore)
CANNOT define a variable starting with numeric/digits.
There are three Data types in Perl. (Data types are raw data stored in a variable.)
* Scalar
* Array
* Hash
Global Variables
Global Variables once declared is available through out the scripts.
"use strict" - is a module for proper coding which is included in a perl script to use strict variable, i.e variables has to declared first before assigning value. Eg;
#!/usr/bin/perl
use strict;
our $name = "kambui\n";
my $variable = "happy\n";
We declare Global variable using "our"statement and Lexical Variable using "my". This is not mandatory if the use script module is not in use.
Lexical Variables
Variables declared is only available for the specific block instead of the whole script.
BLOCK -This is a section of a script which isolate the use of Lexical variables.
Start with {
Ends with }
Eg:
#!/usr/bin/perl
use strict;
our $name = "kambui\n";
print "$name";
{
my $name = "avik\n";
print "$name";
}
#END
Result :
kambui
avik
To set a variable via Standard in (keyboard input)
print "type your name\n";
my $name = ;
Scalar Variable - Scalar variable is nothing but a single value or a result stored in singular representation.
To Set a scalar variable use the $ sign eg:
$firstname = "Avik"
To print the above ;
print "$firstname\n";
Array Variable - Array variable stores a list of scalars or number of result stored in singular representation.
To Set a scalar variable use the @ sign eg:
@name = ("avik","vik","cams","rams");
Remember array called @name is different from a scalar called $name. So we can have both of them in a the same script without any conflict.
Examples;
@name = ("avik","vik","cams","rams");
To print the above we can use;
print "$name[0]";
print "$name[1]";
print "$name[2]";
print "$name[3]";
Notice the position of an element in an array. print "$name[0]"; will print avik and so on. Also notice that while printing the array we use $ instead of @ .
However to print an array in one single statement we can use print "@name[0,1,2,3]\n";
Hash Variable - Hash variable stores a list of key value pairs in a singular representation.
To Set a hash use the % sign eg:
%name_birth = ("avik","july","namrata", "dec");
to print the above '
print $name_birth{"avik"}\n;
output will be : july
Another layout representation of hash
%name_day = (
avik => "wed"
namrata => "thus"
);
Use of keys values of a hash with an array.
@name = keys %name_day;
@day = values %name_day;
print "@name[0..$name]\n";
print "@day[0..$day]\n";
The above will output :
avik namrata
wed thus