Introduction to Perl
What is Perl
Perl is an interpreted language. This means you run it
through an interpreter, not a compiler. Similar to shell script but lot easier and more powerful.
Perl is free to download and is also available for Windows
and Macintosh.
How to run perl: our program/script must first tell the
system where the interpreter is located
#!/usr/bin/perl
One more step…
Must tell the OS that this is an executable file. Use chmod Usually only need to give yourself execute permissions. Once it‟s executable, type the filename at a prompt, and it
runs.
Variables
Three (basic) types of variables.
Scalar Array Hash
Scalars
Scalar means “single value” In C/C++, many many different kinds of single values:
int, float, double, char, bool
In Perl, none of these types need to be declared
Scalar variable can hold all these types, and more.
Scalars
All Scalar variables begin with a $ next character is a letter or _ remaining characters letters, numbers, or _ Variable names can be between 1 and 251 characters in
length Examples: $foo, $a, $zebra1, $F87dr_df3
Scalar Assignments
Scalars hold any data type: $foo = 3; $d = 4.43; $temp = „Z‟; $My_String = “Hello, I‟m Paul.”
$value = TRUE;
Arithmetic in Perl
$a = 1 $a = 3 $a = 5 $a = 7 $a = 9 $a = 5 + 2; - 4; * 6; / 8; ** 10; % 2; # Add 1 and 2 and store in $a # Subtract 4 from 3 and store in $a # Multiply 5 and 6 # Divide 7 by 8 to give 0.875 # Nine to the power of 10, that is, 910 # Remainder of 5 divided by 2
8
String and assignment operators
$a = $b . $c; # Concatenate $b and $c
9
Single and double quotes
$a = 'apples'; $b = 'bananas'; print $a . ' and ' . $b;
prints: apples and bananas
print '$a and $b';
prints: $a and $b
print "$a and $b";
prints: apples and bananas
10
Arrays
Concept is the same as in C/C++
Groups of other values Groups of scalars, arrays, hashes
much more dynamic than C/C++
no declaration of size, type can hold any kinds of value, and multiple kinds of values
All array variables start with the @ character
@array, @foo, @My_Array, @temp34
Array assignments
@foo = (1, 2, 3, 4); @bar = (“hello”, “my”, “name”, “is”, “Paul”); @temp = (34, „z‟, “Hi!”, 43.12); Arrays are 0-indexed, just as in C/C++ $temp[1] = „x‟;
NOTE: This is a *single value*, hence the $
@temp now: (34, „x‟, “Hi!”, 43.12)
merge array:
@result = (@foo, @bar); @result now: (1, 2, 3, 4, “hello”, “my”, “name”, “is”, “Paul”)
More about arrays
special variable for each array: @foo = (3, 25, 43, 31); $#foo (a variable: last index of @foo, which is 3). $foo[$#foo] (a variable: last element in @foo, which is 31). This can be used to dynamically alter the size of an array: $#foo = 5; #creates two null values on the end of @foo $#foo = 2; #destroys all but the first three elements of @foo “Slices” – part of an array @bar = @foo[1..3]; # @bar==(25, 43, 31) @bar = @foo[0,1]; #@bar ==(3, 25)
Hash Table
Associate keys with values – named with % Examples
$wordfrequency{"the"} = 12731; # creates key "the", value 12731 $phonenumber{“My Name"} = “1-574-520-5067";
Hash Operations
%birthdays = ("An","25-02-1975","Bert","12-10-
1953","Cindy","23-05-1969");
# fill the hash
%birthdays = (An => "25-02-1975", Bert => "12-10-
1953", Cindy => "23-05-1969");
# fill the hash; the same as above, but more explicit
%bdays = %birthdays; # copy a hash
Operations on Hash
keys HASH returns a list with only the keys in the hash. values HASH returns a list with only the values in the hash, in the
same order as the keys returned by keys.
foreach $key (sort keys %hash ) { print "Key $key has value $hash{$key}\n"; }
Comments
The pound sign "#" is the symbol for
comment entry. There is no multiline comment entry , so you have to use repeated # for each line. But the first line, #!/usr/bin/perl, tells where to find the Perl compiler on your system
Basic IO: Output to terminal
the print statement. Examples:
print print print print print
“Hello World\n”; “My name is $name\n”; “Hi ”, “what\’s ”, “yours?\n”; 5 + 3; ((4 * 4). “\n”);
Input from keyboard
read line operator: <>
aka “angle operator”, “diamond operator”
Encloses file handle to read from. Defaults to STDIN, which is what we
want.
$input = <>;
read one line from STDIN, and save in $input
@input = <>;
read all lines from STDIN, and save as array in @input
Chop & Chomp
When reading in, carriage return (“\n”) is included. Usually don‟t want that. chomp will take off the last character of a string, if it is a
“\n”. chop takes off last character of a string, regardless of what it is.
Hence, chomp is “safer”.
chomp ($foo = <>);
Very common method of reading in one string from command
line.
Read / Write to Files
To read and write to files we
should create something called handles which refer to the files. To create the handles we use the OPEN command. open(filehandle1,"filename");
Will create the handle called
filehandle1 for the file "filename". This handle will be used for reading.
Read / Write to Files
open(filehandle2,">filename");
Will create the handle called filehandle
2 for the file "filename". This handle will be used for writing. Watch out for the ">" symbol before the filename. This indicates that the file is opened for writing.
Read / Write to Files
Once the file handles have been
obtained. the reading and writing to files is pretty simple. $linevalue = ; This will result in a line being read from the file pointed by the filehandle and the that line is stored in the scalar variable $linevalue.
Read / Write to Files
print FILEHANDLE2 "$linevalue\n"; This will result in a line with the value as in $linevalue being written to the file pointed by the filehandle2 . For closing a filehandle use close(FILEHANDLE);
Program Flow
Blocks
{
statement1; statement2;
}
Program Flow
conditions
if ($x == $y) { #... } elsif ($x == ($y+1)) { #... } else { #... }
Program Flow
Comparing variables Strings eq ne lt gt Numbers == != < >
Program Flow
Logical operators && || ! and or negation
Program Flow
loops for ($t = 0; $t < 100; $t++) { #... }
while ($x == $y) { #... }
Program Flow
foreach Statement This statement takes a array of
values and assigns them one at a time to a scalar variable, executing a block of code with each successive assignment. For example, @list an array
foreach $var (@list) { # }
Subroutines (functions)
To define your own subroutine, use the keyword „sub‟ Can be defined anywhere in your program
Function Calls
$Name = getname(); #return a value getname(); #not returning a value
Parameters of Functions
We can pass parameter to the
function as a list . The parameter is taken in as a list which is denoted by @_ inside the function. So if you pass only one parameter the size of @_ list will only be one variable. If you pass two parameters then the @_ size will be two and the two parameters can be accessed by $_[0],$_[1] ....
Subroutines
sub max { if($_[0] > $_[1]) { return $_[0]; } else { return $_[1]; } } $result = max(11, 12); Print “The largest number is: $result \n”;
What is the output ?
The largest number is: 12
More About Functions
The variables declared in the main
program are by default global so they will continue to have their values in the function also. Local variables are declared by putting 'my' while declaring the variable.
Subroutines: Example
Private variables in Subroutines
sub max {
my($a, $b) = @_ if($a > $b) { return $a; } else { return $b; } }