Tuesday, December 16, 2008

Perl Basics

# Introduction to Basic Perl
>> SHEBANG (#!/usr/bin/perl)
Perl is a script language, which is compiled each time before running. That unix knows that it is a perl script there must be the following header at the topline of every perl script: #!/usr/bin/perl This is known as SHEBANG.
>> Perl Command & Comments
Everything starting from a "#" up to the end of the line is comment and has no effect on the program. Commands start with the first non space charachter on a line and end with a ";". So one can continue a command over several lines and terminates it only with the semicolon.
>> Perl Subroutines & Execution
Direct commands and subroutinesNormal commands are executed in the order written in the script. But subroutines can be placed anywhere and will only be evaluated when called from a normal commandline. Perl knows it's a subroutines if it the code is preceeded with a "sub" and enclosed in a block like: sub name { command;}
Other special linesPerl can include other programming code with: require something or with use something.
QuotationsSingle quote: '' or: q// Double quote: "" or: qq// Quote for execution: `` or: qx// Quote a list of words: ('term1','term2','term3') or: qw/term1 term2 term3/ Quote a quoted string: qq/"$name" is $name/; Quote something wich contains "/": qq!/usr/bin/$file is readdy!;
>> Perl CONTEXT
Scalar and list contextThat perl distinguishes between scalar and list context is the big feature, which makes it uniqe and more usful then most other script languages. A soubroutine can return lists and not only scalars like in C. Or an array gives the number of elements in a scalar context and the elements itself in a list context. The enormous value of that feature should be evident.
>> Perl Variables and Operators
GeneralThere are scalar variables, one and two dimensional arrays and associative arrays. Instead of declaring a variable one preceeds it with a spcial charachter. $variable is a normal scalar variable. @variable is an array and %variable is an associative array. The user of perl does not have to distinguish between a number and a string in a variable. Perl switches the type if neccessary.
ScalarsFill in a scalar with: $price = 300; $name = "JOHN"; Calculate with it like: $price *= 2; $price = $oldprice * 4; $count++; $worth--; Print out the value of a scalar with: print $price,"\n";
ArraysFill in a value: $arr[0] = "Fred"; $arr[1] = "John"; Print out this array: print join(' ',@arr),"\n"; If two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;
Hashes (Associative Arrays) Fill in a single element with: $hash{'fred'} = "USA"; $hash{'john'} = "CANADA";
Fill in the entire hash:
%a = (
'r1', 'this is val of r1',
'r2', 'this is val of r2',
'r3', 'this is val of r3',
);
or with:
%a = (
r1 => 'this is val of r1',
r2 => 'this is val of r2',
r3 => 'this is val of r3',
);