Sunday, April 1, 2012

perl scripting




###### Perl Scripting #######

Practical Extraction and Reporting Language
Perl is a popular Language
It allows us to manipulate data, specially text data in various ways

- Perl is a programming language which can be used for a large variety of tasks. A typical simple use of perl would be of extracting, Information from a text file and printing out a report or for converting a text file into another form. But perl provides a large number of tools for quite complicated problems, including systems programming.


- Programs written in Perl are called perl scripts, whereas the term the perl program refers to the system program named perl for executing


perl scripts

- If you have used shell scripts or awk or sed or similar(Unix) utilities for various purposes, you will find that you can normally use

perl for those and many other purposes, and the code tends to be more compact.


Advantages:


Perl is by far the most widely used language for CGI programming! It contains many powerful features, and is very easy for the novice


programmer to learn. The advantages of perl include


- It is highly portable and readily available

- It contains extremely powerful string manipulation operators, as well as functions to deal with binary data
- It contains very simple and consice constructs
- It makes calling shell commands very easy, and provides some useful equivalents of certain UNIX system functions
- There are numerous extensions built on top of perl for specialized functions; for example, there is oraperl(or the DBI Extensions), which xargs do_something but this will execute the do_something for every file. Sometimes that's just unnecessary overhead in other cases it is impossible to use this as you need to maintain information between calls

- Monitor User behavior especially disk usage

- Writing an excelsheet

Version Perl: perl -v

First line of script: #!/usr/local/bin/perl
Executable file: chmod +x test.pl
For CGI or pl script: print ("Content-type:text/html\n\n");

Comment: #this comment the line

Print: print "Hello !!!"
Numeric and String Literals

A literal is a value that is represented "as is" or hard-coded in your source code.


- Numbers - This is the most basic data type

- Strings - A string is a series of characters that are handled as one unit
- Example of Number : 1,2.3,4,(45)10,etc
- Example of Strings 'David Marchall\'s,"David Marshall\n",`dir *.txt`

It is a Interpreted Language

PERL:- Practical Extraction Reporting Language
- Perl is a modular language, we can enable extensibility
- Perl is procedular Language
- It supports Object Orientation
- Standalone Executable, it can call multiple Binaries

perl -v

( Typically by any opensource software, the later the version, the better the software )
cpan.org

In linux/Unix system there is no relevance of file extensions, unlike Windows


Example

#!/usr/bin/perl -w ( w - echo any error by the interpreter/ syntax error )
# Author: Gyani Pillala
# Date: 3 Apr 2011
# Purpose: Blogging
print "Hello world\n"; // Hello world
print 'Hello world\n'; // Hello world\n
print "29\n"; // 29

# When we use ' single quotes inside the perl, the contents are literally printed

It always important to run the script with ( w ) option

#perl -w script.pl

' - single quotes literals. Anything with in the single quote are not inter-porelated
" - double quotes Inter-porelation. Anything within the double quotes will be inter-porelated even spaces

Unlike shell script which execute line-by-line

perl compiles the script into a internal format, before actually executing the script
unlike bash (shell scripting ) , perl is programming language

## Quoting Nuances

With in single quotes we can print Double quotes
with in double quotes we can print single quotes
$name = "Gyani";
print '$name\n " ';
print "Aren't you happy?";
print '$Gyani\n " ', "\n", "\t";
print "Aren't you happy?", "\n";

Escape Character #\ - Escape character for Perl BASH

print "c:\windows"; // c:windows

print "c:\\windows"; // c:\windows  ( We have escaped the \)

print "c:\\Documents and Settings", "\n";

print q{'' "" }; \\ '' " "

print qq(\n$name\n); or qq{\n$name\n}  \\ Gyani

## Variables

There are 3 types of Variables
scalar, arrays, hashes

The basic datatype of perl is scalar

scalar variables store single variable
example: word,name,spacces etc
To explain Scalar Variable

$firstname = "Gyani\n";

print "$firstname";

$firstname = "Gyani ";

$lastname = "Pillala\n";
$age = 29;
$floatingtest = 2.999;
print "$firstname $lastname is age: $age\n";

Demonstrate proper variable declaration techniques

# Global Variables
$firstname = "Gyani";
$age = 29 ;
Once you turn on "use strict " module in perl, we need to declare the variables Local/Global

my - local variable

our - Global variable

#!/usr/bin/perl

use strict;
my $firstname = "Gyani";
my $age = 29;
our $count = 1;

print "Count is set to: ", "$count", "\n";

# Variables in Perl MUST begin with (aA_)
# Cannot define variable with numeric. e.g. $101Park
# Underscore is reserved keyword, Being used to declare variables and functions

my $_101Park = 101; // It works

print "$_101Park", "\n";

# Block Definition

{
my $firstname = "LinuxPERL";
my $age = "2";
print "$firstname is $age years young", "\n";
print "count is: $count \n";
}

Howto Get value/data from Stdin.


print "Please tell us your first name\n";

my $firstname = ;
print "$firstname is $age years young", "\n";

Arrays are lists of Scalars

# Scalars = single value - $var = "value";
# Arrays = Lists of scalars - @var = ("","");
# Hashes = Key/value pairs - %

@carmanufacturers = ("honda", "Toyota", "nissan","lexux");

print "$carmanufacturers[0] ";
print "$carmanufacturers[1] ";
print "$carmanufacturers[2] ";
print "$carmanufacturers[3] \n";
print "This array contains $#carmanufacturers elements\n";
print "@carmanufacturers[0,1,2,3,4]";
print "@carmanufacturers[0..4]\n";

#Arrays

@array = (1,2,3);
@copy_array = @array
@array2= (1,2,3,@array1,7,8);
@array2=(1,2,3,4,5)
@array1[1] = $array2[3];

Variables

Scalar -- denoted by a $ symbol prefix. A scalar variable can be either a number string
Array -- denoted by a @ symbol prefix. Arrays are indexed by numbers
Associative Array -- denoted by a % symbol prefix. Arrays are indexed by strings. you can look up items by name.

Note: Variables names in perl are case-sensitive. This means that $varname, $VarName


some usefule Array functions:

Push() and pop()
Shift and unshift
reverse()
chop()
chomp()

Example of Associative Array

%lookup=("dave",1234,"peter",3456,"andrew",6789);
@name=keys(%lookup)

Example:

$a=3
Post Increment
$d=$a++ ( The values will be d=3, a=4)
Pre Increment
$d=++$a (d=4,a=4)

#perl -c demo.pl (Compile the perl code )

#perl demo.pl (Execute the perl code )

- Statements are a complete unit of instruction for the computer to process

- Simple Expressions
- simple Expressions with Side Effects
- Simple Expressions with Operations
- Complex Expressions

#Hash

hashes are key-value pairs
counties-currency

$firstname = "Gyani"; #This is a scalar variable type

@fullname = ("Gyani", "Andrew", "Pillala " ); # This is an Array

%make_model = ("Honda", "Accord", "Toyota", "Camry"); # This is a default Hashing way

print "Honda makes the :";
print $make_model{"$make"};

$player = "Sharapove";

%player_country = (
Venus => "USA",
Sharapova => "Russia",
);
print "$player represents: ";
print $player_country { "$player "};
print "\n"

@num_of_players = keys %player_country;

print "@num_of_players[0..$#num_of_players] \n"; // o/p - venus,sharpova

@num_of_players = values %player_country;

print "@num_of_players[0..$#num_of_players] \n"; // o/p - usa,russia

@players = keys %player_country;
@values = values %player_country;

print "@players[0..$#players] \n";

print "@values[0..$#values] \n ";

@fullname = ("Gyani", "Andrew", "Pillala");  #This is a Hash

print "@fullname[0..$#fullname]"; // prints the entire Array


## Statements

A statement block is a group of statements surrounded by curly braces

Example:

sub areaOfCircle=areaOfCircle(5);
print("$areaOfFirstCircle\n");
sub areaOfCircle {
$radius = $_[0];
return (3.14 *($radius**2));
}

Using the Parameter Array(@_)

areaOfRectangle(5,6);

sub areaOfRectangle{

($height,$width)=@_;
$area=$height* $width;
print(The height is $height. The width is $width. The area is $area. \n\n");
}

Using a List as a Function Parameter

firstSub("AAAA",(0..10));

sub firstSub{

local($firstVar,@array)=@_;
print("firstSub: array = @array\n");
print ("firstSub: firstVar=$firstVar\n");
}
This program prints:
firstSub array = 0 1 2 3 4 5
firstSub: firstVar = AAAA
Scope of Variables: my,local,our
Nesting Function Calls: calling one function into another

Using a List as a Function Parameter

firstSub("AAAA",(0..10));

sub firstsub{

local($firstVar,@array)=@_;
print("firstSub:array=@array\n");
print("firstsub:firstVar=$firstVar\n");
}

This program prints:

firstSub: array = 1 2 3 4 5 6 7 8
firstSub: firstVar=AAAA

Scope of Variables=my,local,our

Nesting Function calls: calling one function into another


-- String Functions --

-chomp(STRING) OR chomp(ARRAY) -- Uses the values of the $/ special variable to remove endings from STRING or each element of ARRAY. The
line ending is only removed if it matches the current value of $/.

-chop(STRING) OR chop(ARRAY) -- Removes the last character from a string or the last character from every element in an array. The last character chopped is returned


-chr(NUMBER) -- Returns the character represented by NUMBER in the ASCII table. For instance, chr(65) returns the letter A.


-crypt(STRING1,STRING2) -- Encrypts STRING1..Unfortunately, perl does not provide a decrypt function


-index(STRING,SUBSTRING,POSITION) -- Returns the position of the first occurrence of SUBSTRING in STRING


length(STRING) - Returns the length of STRING


split()

substr(STRING,OFFSET,LENGTH)

With Array 1st string is - zero th element

with String 1st character is - 1st element


Array Functions

-Arrays are also a big part of the Perl language and Perl has a lot of functions to help you work with them. Some of the actions arrays perform including deleting elements, checking for the existence of an element.

- Here are the functions you can use with arrays:

- defined(VARIABLE) -- Returns true if VARIABLE has a real value and if the variable has not yet been assigned a value. This is not limited to arrays; any datatype an be checked. Also see the exists function for information about associative array keys
-delete(KEY) - Removes the key-value pair from the given associative array. If you delete a value from the %ENV array, the environment of the current process is changed, not that of the parent
- each(ASSOC_ARRAY) -- Returns a two-element list that contains a key and value pair form the given associative array. The function is mainly used so you can iterate over the associative array elements. A null list is returned when the last element has been read.
- exists(KEY) -- Returns true if the KEY is part of the specified associative array. For instance, exists($array{"Orange"}) returns true if the %array associative array has a key with the value of "Orange"
- join(STRING,ARRAY) -- Returns a string that consists of all of the elements of ARRAY joined together by STRING. For instance,join(";;",("AA","BB","cc")) returns "AA;;BB;;cc".
-keys(ASSOC_ARRAY)-- Returns a list that holds all of the keys in a given associative array. The list is not in any particular order
-map(EXPRESSION,ARRAY)-- Evaluates EXPRESSION for every element of ARRAY. The special variable $ is assigned each element of ARRAY immediately before EXPRESSION is evaluated


-- References --

Reference Assignment How to Dereference

$refScalar=\$scalar; ${$refScalar} is a scalar value

$refArray=\@array; @{$refArray} is an array value
$refHash=\%hash; %{$refHash} is a hash value
$refglob=\*file;
$refRef=\$refScalar; ${${$refScalar}} is a scalar value


Example

@array1 =(1..5);
@array2 =("A".."E");
firstSub(\@array1,\@array2); #One
sub firstSub {
my($ref_firstArray,$ref_secondArray)=@_; #Two
print("The first array is @{$ref_fristArray},\n"); #Three
print("The second array is @{$ref_secondArray},\n"); #Three
}

This program displays:

The first array is 1 2 3 4 5
The second array is A B C D E

ref{$ref_secondArray)eq "ARRAY"

Function Call Return Value

ref(10); undefined

ref(\10); SCALAR
ref(\{1 ;;"Joe"}); HASH
ref(\\10); REF

Example:

"MRD-250" =; ( "Name" =; "Kevin Hughes",
"Address" =; "123 Allways Dr.",
"Town" =; "AnyTown",
"State" =; "Anystate",
"Zip" =; "12345-1234"
}
print (%{$database{"MRD-100"}};{"Name"} "\n");

Example:

print ("Here are 5 dashes ${\makeLine(5)}.\n");
${\nmakeLine(5)).\n");

print("Here are 10 dashes

${\makeLine(10)}.\n");

-- File input and output

The three special file handles are always open STDIN,STDOUT and STDERR

perl -w 091st01.pl ; 09lst01.pl this redirect it output.

Diamond operator (<>);;. @ARGV
There are many other function which are unix commands like chown,close,eof,closedir,etc we can cover it in next session


-References

%recordOne=("Name" ; "Jane Hathaway",
"Address" =; "123 Anylane Rd.",
"Town";"AnyTown",
"State" ; "AnyState",
"Zip" ; "12345-1234"
);

%recordTwo=("Name";"Kevin Hughes",

"Address";"123 Allways Dr.",
"Town";"AnyTown",
"State";"Anystate",
"Zip";"12345-1234"
);

@database=(\%recordOne,\%recordTwo);

you can print the address member of the first record like this;
print(%{$database[0]};{"Address"}."\n");
which displays: 123 Anylane Rd.

## funtions ##

Sub Routines
Allows us to arrange the code in logical, allow us to neatly presently our code, frequntly executing the code

Example:

use strict;
testsub(); # Default way to call a sub-routine
testsub1

sub testsub {

my $name = "Gyani Pillala";
print "Hello", "$name\n";
}

# Passing parameters to the functions

testsub("Gyani");
sub testsub {
print "hello", "$_[0]\n"
or
testsub("Gyani","Pillala")
0/p: Hello Gyani
     Hello Pillala

sub testsub {

print "Hello ", "@_\n";
}
o/p: Hello Gyani Pillala

Note: Debugging can be done very easily, if we have a funtions in bash/perl

Note: unlike in bash, we have to define the code and then call the function. In perl it doesn't matter we can call the function before the function definition or after it doesn't matter. Because perl compiles the code before it runs.

Example:

#!/usr/bin/perl -w
use strict
testsub();  # default way to call a sub-routine
sub testsub {
my $name = "Gyani Pillala";
        print "hello ", "$name\n";
}

#passing parameters in function

Example:
testsub("Gyani");
sub testsub {
     #  print "Hello", "$_[0]\n";
        or
     foreach(@_) {
               print "Hello ", "$_\n";
   }
}
or
testsub("Gyani","Pillala");
sub testsub {
print "Hello ", "@_\n";   # @_ represents complete array
}
o/p: Hello Gyani Pillala

Example: Opening a file handle, good to use subroutine

Note: subroutine is treated like anyother variable in perl enviroment
Foreach will go through each elements in the list

Example:

#!/usr/bin/perl
use warnings;
use strict;
open (han1, ">> logfile.sub") || die "Errors opening file: $!";
my $etcdir = `ls -l /etc/passwd`
chomp $etcdir    ## To get a new line
my $message = "Launching sub2.pl";
log_message("$message");
log_message("$etcdir");

sub log_message {

my $current_time = localtime;
        print "$current_time - $_[0]","\n";
        print han1 "$current_time - $_[0]", "\n";   ## This is where the log File is being called "han1"
}

### Multi-Dimensional Arrays  ###

#!/use/bin/perl -w
#Purpose: Arrays and Growing of Arrays from file
@array1 = (["1","2"],["3","4"],["5","6"]); # multi-dimensional typical array
print "$array1[2][0]\n";  # o/p - 5

Note: In order to change the typical multi-dimensional array to reference array, we need to just remove the open brackets and put square brackets


# Reference multi dimensional Array

Note: Reference is an Scalar Value
$array1ref = [["1","2"],["3","4"],["5","6"]];  # multi-dimensional reference array
print $array1ref->[0][0] # o/p - 1

# Multi-Dimensional Array2 # creating dynamic array with data feeds available in array

Typicall we have to read a file which contains Gyani pillala ... we need to populate a array with push function.

Purpose: Arrays and Growing of Arrays from file


#!/usr/bin/perl -w

open(HAN1, "data1") || die "Errors opening data1 : $!";  # Die will be called, when there is a problem is opening a file
while ()   # Until you get to the valid endof File
{
push @array1, [ split ]   # perl will understand anonymous error and data will split eventually lead to double dimensional array
# Push function ability to push the data into the array
# If you recall, many of the functions will operate on default variables that generate through loops
}

foreach (@array1) {

print "@$_\n";  # printing the Multidimesional array(@$_)
}
print "\n\n$array1[0][1]\n";

Note:

Open data4 another file having content
Gnu/linux scripting testing
Gyani Pillala Gnu
We can use the above program to parse the content, it will work

### Array Slices ###

Purpose: Lists, Slices, Hashes(Key/value pairs)
Note: print operates on both scalar and lists
print (qw(Boston Charlotte Newark Miami));
Note: qw allows us to define a list and seperated by space

#Example

#!/usr/bin/perl -w
use strict;

my @uscities = qw(Boston harlotte Neuswark Miami);

print "@uscities\n";
 o/p: Boston harlotte Neuswark Miami
        print "@uscities[0,1]\n";
 o/p: Boston harlotte
        print "@uscities[0..$#uscities]\n";  # print the entire Array till the last elements

my @eastcoastcities = @uscities[0..3];

or
my @eastcoastcities = @uscities[0..3,7,8];  # In this way also we can derive an array from master Array
print ("East Coast Cities:", "@eastcoastcities\n");
print ("Other Cities:", "@uscities[4..$#uscities]\n");

### Array Functions ###

Purpose: Demonstrate Common Array Functions
Example:
use strict;
my @array1 = ("1","2","3");
print "@array1\n";  # 1 2 3
my $ppop = pop @array1;
  print "@array1\n";  # 1 2
Note: pop and push works at the ends of the array
push @array1, $ppop;
print "The array now contains:", "@array1\n";  # 1 2 3
Note: We can push string also
my $firstname="gyani";
my $middlename="pillala"
push @array1 $firstname;
print "The array now contains:", "@array1\n"; ## 1 2 gyani
unshift (@array1, "$firstname","middlename"); # add the contents of $firstname to array1 at the begining of the array
print "After using Unshift:", "@array1\n";  ## gyani pillala 1 2 gyani
Note: unshift is use to prepend into the array
Note: shift totally remove the first element from the array

shift @array1; #remove the value from the first element from the array

print "After using Shift:", "@array1\n";   # pillala 1 2 gyani
#END

Note:

sort is very good, when you have strings in an arrays
my @array1 = sort @array1;
print "After using Sort:", "@array1\n";

### Conditionals ###

if Decission Making

if (condition) {

>= # Integers
>  # Integers
<  # Integers
ge le eq ne # strings
}
Example :
if ( 1 < 2 ) {   # condition (2 = 2) will fails, bcos single equals means Assigning value from right to left, Integer comparision (==)
print "1 is less then 2\n"
}

Example:

$value1 = 1
$value2 = 2
$firstname = "Gyani";
$nickname = "Demo";

if ( $value1 <= $value2 ) {

print "$value1 is equal to $value2\n";
}
  elsif ( condition ) {      # Within the parent If condition
    }

if {$firstname eq $nickname ) {

print "$firstname is equal to $nickname\n";
}
else {
print "$firstname is NOT equal to $nickname\n";
}

# Will be true when it gets boolean false

unless ($value1 == $value2) {        # This condition will only successed, when this condtion will fail
print "$value1 is NOT equal to $value2 \n\n"
}

## OneLiner

print "This is a one liner " if $value1 == $value2 ;
print "This is a one liner " unless $value1 == $value2 ;

## Positional Parameters ##

How to extract Command Line Arguments
Scalar, Array, Hashes - @ARGV
print "$ARGV[0]\n";   ## prints the first value runtime value
print "$#ARGV\n";     ## prints the count of runtime variables
O/p:
#./posparam1.pl
-1
#./posparam1.pl testargg1
0
ARGV is always the total (-1)
To get the total number of runtime parameters passed
$#ARGV +=1;
print "$#ARGV\n";     #Prints the total number of Arguments

$REQPARAM = 3;

$BADARGS = 165;
$#ARGV +=1;
unless ($#ARGV == 3) {
print "$0 requires $REQPARAM arguments\n";
exit $BADARGS;
}
print "$ARGV[0] $ARGV[1] $ARGV[2]\n";
print "@ARGV[0..$#ARGV]\n";

## For Loops ###

$min = 3;
$max = 23;
$PROD_NAME = "LinuxPERL Scripting Edition";
for ($i=$min; $i<=$max; $i++) { print "$i\n";}
for ($min..$max) { print "$PROD_NAME\n";}
# END
foreach # It is pretty cool, works as a iterator
@array1 = ("Gyani","LinuxPERL","Scripting","Debian","Redhat");
foreach (@array1) {
print "$_\n";  # Prints the entire Array elements

}
$#array1 +=1;
print "Total Array Elements = $#array1\n"; # Prints the count of Array elements
NOTE: Anything which is initialize... takes the memory

## Basic while and Until Loops ##

$value1 = 1;
$value2 = 2;
while ($value1 <= $value2) {
print "$value1\n";
$value1 +=1;
}

Until Loops ( Check for False value in the condition...it iterates until it is true )

$value1 = 1;
$value2 = 20;
$firstname = "Gyani";
$lastname = "Pillala";
until ($value2 <= $value1) {
print "$value2\n";
$value2 -=1;
}


--File Input and Output

opendir(DIR,"./Internet")
die "NO SUCH Directory:Images";

foreach $file (sort readdir(DIR)) {

print " $file\n";
} closedir(DIR);

Therefore to read from one file infile and copy line by line to another outfile we could do readwrite.pl

open(IN,"infile")
die "cannot open input file";
open(OUT,"outfile")
die "cannot open output file";
while(){
print OUT$_; #echo line read
}
close(IN);
close(OUT);

- Special pattern matching character operators

In particular the following metacharacters have their standard egrep-ish meanings:
\ Quote the next metacharacter
^ match the beginning of the line
. match any character (except newline)
$ match the end of the line(or before newline at the end)

Alteration

() Grouping
[] Character class
[012345679] #any single digit
[0-9] # also any single digit
[a-z] # any sigle lower case letter
[a-zA-Z] #any sinlge letter
[0-9\-] #0-9 plus minus character

The caret(^) can be used to negate matches

[^0-9] #any single non-digit
[^aeiouAEIOU]# any single non-vowel

### File I/O  - 1 ###

Basic File I/O capabilities
$min = 1;
$max = 20;
$fullname = "Gyani Pillala";
- open (OUTFILE, "data1")   #  Read mode
- open (OUTFILE, ">data1")  # Write mode
- open (OUTFILE, ">>data1") # write and Append mode
open (OUTFILE, ">data1") || die "Problems: $!"; # Opens a file, if file not existing creates a file
#open and die functions... when we are working with file. we are working with file handle...that is memory
# representations
#perl maintains a internal variable called "$!",, it stores the errors in the variable

for ($min..$max) { print OUTFILE "$fullname\n";}

print file accepts the arguments as file handle

## File I/O ##

#data1 - contains -- Gyani Pillala
open (INFILE, "data1") || die "Problems: $!";
while () {
print "$_";
}
$IN = "INFILE";
$OUT = "OUTFILE";
$filename = "data1";
open ($IN, "$filename") || die "Problems: $!";
@data1contents = ;
foreach (@data1contents) {
print $_;
}

$IN = "INFILE";

$OUT = "OUTFILE";
$filenamein = "data1";
$filenameout = "data2";
open ($IN, "$filenamein") || die "Problems: $!";
open ($OUT, ">$filenameout") or die "Problems writing to file: $!";

@data1contents = <$IN>;
foreach (@data1contents) {
# s/Gyani/Gyanio/;     # Replaces the Gyani word to Gyanio
if (/Gyani/) {    # line matching the word
print $OUT $_;
}
}

$FILEHANDLE = "FILEREADWRITE";

$filename = "data1";
$appendtofile = "Append";
open ($FILEHANDLE, "+<$filename") || die "Problems: $!";
# +<$filename -- Open for reading and appending as well
@data1contents = <$FILEHANDLE>;
foreach (@data1contents) {
s/Gyani/Gyanio/;
# print $FILEHANDLE $appendtofile;
}
print $FILEHANDLE "$appendtofile\n"

# NOTE - + will allow to read/write the file

# < (append)    >(truncate, make the file to zero)   +>>(class append redirection)

open ($FILEHANDLE, "ps -ax | " ) || die "Problems: $!";

@data1contents = <$FILEHANDLE>;
print "$_";

Example:

open ($FILEHANDLE, "netstat -ant |") || die "Problems: $!";
@data1contents = <@data1contents){
if (/80/) {
print "$_";
}

Directory Listings

$DIR = "/etc";
$DIRHANDLE = "HANDLE";
opendir ($DIRHANDLE, "$DIR") || die "Error opening $DIR: $!";
@dirlist = readdir($DIRHANDLE);
foreach (@dirlist) {
print "$_\n";
}
$DIR = "/tmp/perl";
@dirlist = `ls -A $DIR`;
foreach (@dirlist) {
print "$_";
}

### File I/O split ###

Split , Join, and flexible input files from Shell
@ARGV[0..100] # Pass in command line arguments
NOTE:
Anything in between two forward slashes is considered has regular expression
$data4 = "Gyani"Pillala"; #Scalar value
@array1 = split /:/, $data4; # space in perl mean \n, \t, \s+..
foreach(@array1) {
print "$_\n";
}
$lc = 0;
while (<>) {  # Diamond operator will expect you to specify a filename on command line
print "$_";
@array2 = split /:/, $_;
$lc +=1;
}
print "Line Count is equal to:", "\t", "$lc", "\n";

O/P: #perl -w split1.pl data4

Line Count is equal to: 4

### File I/O split ###

$lc = o;
while (<>) {
print "$_";
@array2 = split /:/,$_;
foreach(@array2) {
print "$_\n";
}
$lc +=1;
}
print "Line Count is equal to:", "\t", "$lc", "\n";

#JOIN

use strict;
my @array1 = ("Gyani", "Andrew", "Pillala");
my $newarray1 = join ",", @array1; #Join interposes delimeter between array$
print "New Delimiter should be \":\" ", "$newarray1", "\n";

use strict;

open (HAN1, ">data4a") || die "Problems: $!";
while (<>) {
my @array1 = split /:/,$_;
my $newarray1 = join ",", @array1;
print "New records are delimited by \",\": ", "$newarray1\n";
print HAN1 $newarray1;
}

NOTE: <> this particular diamond notation can operate on multiple files


## File I/O split ##

use warnings;
use strict;
my $data1 = "dataproducts1";
open (han1, "$data1") || die "Errors opening file $data1: $!";
my @f1 = ;
my $total = 0;

foreach(@f1) {

print "$_";
}

When perl reads the file, it preserves the trailing new line characters !


use warnings;

use strict;
my $data1 = "dataproducts1";
open (han1, "$data1") || die "Errors opening file $data1: $!";
my @f1 = ;
my $total = 0;
foreach(@f1) {
# print "$_";
my @columns = split;
$total = $columns[3] + $total;
}
print "Grand Total for all products found: ", "$total", "\n";

## File I/O Rename ##

Functions and rename files based on case

open (HAN, "teststrings.txt") || die "Problems: $!";

@f1 = ;
foreach(@f1) {
print "$_";
$new = lc; # convert to lower case ... uc --convert to upper case
print "$new";
}

--

$DIR = "/root/temp2/perl/file{1,2,3,4,5}";
@filelist = `ls -A $DIR`;
or
$DIR = "/root/temp2/perl";
$FILES = "FILES*";
@filelist = `ls -A $DIR/$FILES`;
foreach(@filelist) {
print "$_";
chomp;
$new = uc;
print "$new";
rename($_,$new);
or
rename($DIR/$_,$DIR/$new);
}

Example:


$DIR = "/root/temp2/perl";

$FILES = "FILE*";
@filelist = `ls -A $FILES`;
foreach(@filelist) {
print "$_";
chomp;
$new = lc;
print "$new";
rename("$DIR/$_","$DIR/$new");

### Regular Expressions

Perl offers the riches facility on regular expressions

$firstname = "Gyani"; # Scalar Variable

if ($firstname =~ /Gyani/) {
print "$firstname\n";
}
#END

if ($firstname =~ /ean/) {     # It matches the regular expressions

print "$firstname\n";
}

Ignoring Case

if ($firstname =~ /Gyani/i )   # Here Gyani - Gyani it matches

$fullname = "Gyani Pillala"; #Scalar Variable


#Anchor Tags - ^ = search at beginning of string

#Anchor Tags - $ = search at end of string

if ($fullname =~ /^pillala$/i) {

print "$fullname\n";
}
#END

To Explain Regular Expressions II

#$fullname = "Gyani pillala"; #Scalar Variable
@array1 = ("Gyani pillala", "pillala Gyani");
foreach (@array1) {
if (/Gyani$/i) {
print "$_\n";
}
}
s/search/replacement/g ( search and replace multiple values )

foreach (@array1) {

s/Gyani/Gyanio/;
print "$_\n";
}

foreach (@array1) {

s/Gyani\s/Gyani/;    # Removes the space after Gyani
print "$_\n";
}

substitutions can be applied to Hashes/Arrays/Scalars


$fullname = "Gyani pillala"; #Scalar Variable

$fullname =~ s/Gyani\s/Gyani/;  # find Gyani trailing space and replace with Gyani no space
print "$fullname\n";

Regular Expressions III


$IN = "INFILE";

$FILENAMEIN = "data1";
$OUT = "OUTFILE";
$FILENAMEOUT = "data2";

# opens the files for both read and write operations

# open ($IN, "+$FILENAMEIN") || die "Problems opening file: $!";

open ($IN, "$FILENAMEIN") || die "Problems opening file: $! ";

open ($OUT, ">$FILENAMEOUT") || die "problems opening file
# > Creates a file on the fly
@filecontents = <$IN>;
foreach (@filecontents) {
if (/^Gyani/i) {    # If the line starts with Gyani non-case sensitive
s/Gyani/Gyanio/;
print $OUT "$_";
}
}

$var1 = "Linuxtutorial 1 2 3 4";

# \d = extracts only digits
$var1 =~ /(\s\d)/; # $1, $2, $3, etc. ()

# Above statement implies grouping...s -space, d -digit

print "$1"  o/p - 1

$var1 =~ /(\s\d)(\s\d)(\s\d)(\s\d)/;  # $1, $2, $3, etc. ()

print "$1 $2 $3 $4\n"; o/p: 1 2 3 4
#END
$var1 =~ /(\w)(\s\d)  o/p: T 1
grouping is a important feature of regular expressions...

Regulare Expression IV

Anything but digit \D
Anything but character \W
Anything within parenthesis is called grouping

Example instance

$time = `date +%r`;
$time =~ /(\d\d):(\d\d):(\d\d)\s(.*)/;
$hour = "$1";
$minute = "$2";
$seconds = "$3";
$tod = "$4";
print "Hour: $hour Minute: $minute Seconds: $seconds TOD: $tod\n";

#Character Clases - Multiple characters that should match

[mnrt] - character class
$_ - current Element

@array1 = ("might", "night", "right", "tight", "goodzight");

foreach (@array1) {
if (/[mnrt]ight/i) {
print "$_\n";
}
}
o/p: might night right tight
#END

#alternates

When we get data from other source, generally the data will be stored in the array format
foreach (@array1) {
if (/dog|cat|bird/i) {  #Either of the elements matches the array elements
print "$_\n";
}
}
NOTE: If we group together the regular expession... the match can be stored in a variable

REGULAR EXPRESSION V

$IN = "INFILE";
$filename = "data3";
open ($IN, "$filename") || die "Error reading file: $!";
while (<$IN>) {
if (/Gyani$/) {  # ending of the line ... /^Gyani Starting of the line
# if (/\t/) tab # if (/\\/) catching the backslash
print "$_";
}
}
Grouping to seperate the objects
The grouping effort put forth here
open ($IN, "$filename") || die "Error reading file: $!";
while (<$IN>) {
if (/(.:)(.*\\)/){
print "$1 $2";  # These variables corresponds to group

REGULAR EXPRESSION VI

open ($IN, "$filename") || die "Error reading file: $!";
while (<$IN>) {
if (/(.:)(.*\\)/){
print "$1 $2\n";
}
}
o/p: c: \documents and settings\

NOTE: We have to escape for the metacharacters

While (<$IN>) {
if (/\+/){
print "$_";
}
}
o/p: 10+20

# print the file without blank lines

while (<$IN>) {
if (/./){  # With period(.) we can ignore the new line or blank lines in file
print "$_";
if (/.y/) # (.) wild card terminating with y  e.g. cry my
if (/..y/) # (.) two characters before y e.g. cry

if (/[a-z]\d+/i) alphabets and digits combination e.g. GyaniPillala04444


if (/.*@.*/) # Email address gyani.pillala@gmail.com

Grouping
if (/(.*) (@) (.*)/)   # Email address grouping
print "$1 $2 $3 \n";  o/p: gyani.pillala @ gmail.com (hostname)

if (/^$/) {   # Catches all the blank lines in the file

print "$_";
}

COMMON FUNCTIONS I

Three ways to talk to the linux system

To demonstrate common ways to interact with shell

exec "ls -Al";  # only problem is it doesn't return exit status
exec "ls -Al" | die " unable to execute the command "

$DIR = "/etc/init.d";

system "ls $DIR";
print "$?\n";

NOTE: system executes the commands from the shell within the subshell and maitains the exit status

system command in perl returns the exist status of the command

$DIR = "/etc/init.d";

@array1 = ("$DIR/httpd","stop");
system (@array1);
print "$?\n";

$DIR = "/etc/init.d";

$SERVICE = "httpd";
@array1 = ("$DIR/$SERVICE", "stop");
system (@array1);
print "$?\n";
if ($? == 0 ) {
print "$SERVICE has been stoped\n";
}else {
print "$SERVICE has already been stoped \n";
}

perl supports command subsitution by backticks (`)

Quicker and Dirty away in perl ... we can also do it by open built function in perl

$DIR = "/etc/init.d/";

$filelist = `ls -Al $DIR | wc -l `;
print "$filelist \n";

$DIR = "/etc/init.d/";

@filelist = `ls -Al $DIR`;
foreach (@filelist) {
print "$_";
}
print "Last element is: $#filelist\n";
#END
NOTE
exec command doesnot return exit status whereas system command returns it

MAIL INTEGRATION I

$MAIL = "SENDMAIL";
open ($MAIL, "| /usr/lib/sendmail -oi -t") || die "Errors with Sendmail $!";
$BODY = "Here is your directory listing";
@dirlist = `ls -Al`;
print $MAIL <<"EOF";
From: Gyani
To: root
Subject: Testing mail from Perl Script

$BODY

@dirlist
EOF

MAIL INTEGRATION II

http://search.cpan.org/

Installation of the perl modules.

Check of the perl modules
e.g. #perl -MMail::Mailers -e 1
Queries the perl internal distribution

CPAN - Comprehensive PERL Archive Network

#perl -MCPAN -e "install Mail::Mailer"

NOTE: Modules in perl typically stores with the extension *.pm and it will store in the library that has been access to


Example

use Mail::Mailer   # Module capabilities will be certainly be available in the script
$from = "root";
$to = "root";
$subject = "Testing Mail Mailer Module";
$BODY = "Here is your directory listing";
$mailer = Mail::Mailer->new();
$mailer->open({ From => $from,
To => $to,
Cc => "gyanipillala"
Subject => $subject,
});
print $mailer $BODY

Good to Go through the perl module usage before we go ahead


FILE TESTS FUNCTIONS

Availability of file/types of file/size of files etc

$file = "test";

if (-e "$file") {
print "$file exists!\n";
} else {
print "$file does NOT exist!\n";
}

NOTE: perldoc -f -X (-e, -z, -f, -d)

File Zero byte... empty file

if (-z "$file") {

print "$file exists and is zero length!\n";
} else {
print "$file is not zero length\n";
}

if (-f "$file")  # Tests Whether the file is actually a file


ON LINUX/UNIX Terminal Just enter the below command the get the docz

#perldoc -f -X

REFERENCES I

# 3 data types: Scalars, Arrays(lists), Hashes(key/Value Pairs)
e.g.
#$fullname = "";
#@fullname = ("Gyani", "Andrew", "pillala");

References

@uscities = ("Boston","Charlotte","New york","San Francisco");
$USC = \@uscities;  ( Scalar Alias pointing to Arrays )
print "@{$USC}\n";

Looping in

foreach (@{$USC}) {
print "$_\n";
}

Anonymous Array

$USC = ["Boston","Charlotte","New York","San Diego","San Francisco"]
foreach (@{$USC}) {
print "$_\n";
}

Standard Hash

%contacts = ("firstname","Gyani","lastname","pillala");
$contacts = \%contacts; # This model references to contacts of the hashes
print ${$contacts} {'lastname'};

or ( Second way to references )


Make Anonymous Hash

$contacts = { firstname => "Gyani", lastname => "pillala" };
print ${$contacts} {'firstname'}; #use rule 1
print $contacts->{'lastname'}; # use rule 2

Reference to Arrays and Hashes make more sense through scalars... we can create more complex

data sets... standard relation databases...

FILE ATTRIBUTES I


use strict;

my @flist = `ls -A file*`;
foreach (@first) {
print "$_";
stat($_); # returns a 13-element array of file attributes (atime/mtime of file ) 0-12

Example:

use strict;
my @flist = `ls -A file*`;
foreach (@flist) {
chomp;
print "$_","\n";
my @stats = stat($_);
foreach(@stats) { # stat command return the 13 array items
print "$_", "\n";
}
}

NOTE: Since you are using the strict, you always have to use my/our when you define variables

atime/mtime stores at the hearder of the file

Bash Calculator

#expr 456 - 344

foreach(@flist) {

chomp;
print "$_", "\n";
my @stats = stat($_);
(my $atime, my $mtime) = ($stats[8],$stats[9]);
print "Access Time: $atime - Mod Time: $mtime", "\n";
if ($atime - $mtime != 0) {
print "File $_ has been accessed", "\n";
my $new_name = "$_".".old";  # Concatenating the file with .old extension
rename($_,$new_name);
}


CGI I  (common Gateway Interface )

typically associated with perl scripts but not necessarily associated with perl scripts
Any scripts which can accepts the request from the web browser and process it on the server and return a response to the client
Example: perl,php,jsp,php,asp

apache - var/www/cgi-bin

defined in the apache configuration files
e.g. ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" we can have multiple script aliases
cd /var/www/cgi-bin
Example: CGI perl script

print "Content-type: text/html\n\n";

print "

Hello World! - Our first Perl CGI script

";

Example: Illustrate basic Perl/CGI


print "Content-type: text/html\n\n";

print "
";

foreach(sort keys %ENV) {

print "
$_
$ENV{$_}
" }
print "
";
CGI Scripting

#!/usr/bin/perl -w

use stict;
print "Content-type: text/html\n\n";
print "Our First HTML Perl From
print "
";

print "Name:

";
print "E-mail:
;
print "";
print "
";print "
";

Example: action1.pl

#!/usr/bin/perl -w
use strict;
use cgi;
my $cgi=new CGI;  # cgi object

print $cgi->header();

print $cgi->start_html("Action Page");
print $cgi->param('name'); "
";
print $cgi->param('email');
print $cgi->end_html();

Prints the name & email address after submitting the form on the browser


PHP gives richer features for web application like SESSION MANAGEMENTS

perl excels at system and network level whereas PHP excels at WEB
It's not like we cannot do with perl WEB, it will be difficult where as PHP can be much easier

PERL ONE LINERS

perl --help
perl will not interpolate anything in the single quotes

#perl -e 'print "Hello world\n";"

#perl -e '$PROD="Gyanipillala"; $VERSION="Scripting"; print "$PROD $VERSION\n";'
#perl -e 'print "This is a \t Tab";'
#awk '{ print $1, $2 }' data1
#perl -ane 'print "@F[0,1]\n";' data1
#perl -ane 'print "@F[0..1]\n";' data1
#perl -F: -ane 'print "$F[0]\n";' /etc/passwd # print the first column users
#perl -F: -ane 'print "@F[0..3]\n";' /etc/passwd
#perl -F: -ane 'print "$F[1]\n"' data4

perl requires (e) switch when we want to work on the oneliner...

Everything enclosed under single quotes
perl -e '' ## Helps to test perl one liner regular expressions
Example: perl -e 'print "This is a \t Tab";'
perl -n (Performs while loop - iteration)

perl -ne 'print "$_";' data1    # $_ variable when we work with the files, $_ prints each line

--Array notation
perl -ane 'print "@F\n";' data1  (It will print the entire file)
perl -ane 'print "@F[0,1]\n";' data1 (It will print the array elements )
--Scalar notation
perl -ane 'print "$F[1]\n";' data1

-ane ( a - array, n - iteration, e - process everything within single quotes )

perl -F:(delimiter) -ane 'print "@F\n";' /etc/passwd
perl -F: -ane 'print "$F[0]\n";' /etc/passwd

MODULES I (plugins )

cpan.org  (comprehensive perl archive network )

When a perl script runs...it looks at the following directories --one liner

perl libraries rely on
perl -e 'print "@INC";'
-- cpan
root]#perl -MCPAN -e shell

--search

cpan> i /SFTP/
cpan>b (bundles)
a - author, b- budle , d - distribution , m - model
cpan>i Archive::Tar (Install)

Windows (ppm) similar to cpan


cpan> install Net::SFTP


-- CPAN on New Install

CPAN --- first no configuration, instead of yes.

cpan> i Net::SFTP   ( To check whether package is installed or not )

cpan> install Net::SFTP  ( Installation command )
cpan> i Bundle::ebx

## CHECK FOR NEW FILES

Example:

#!/usr/bin/perl -w

use strict;
AscertainStatus();

sub AscertainStatus {

my $DIR = "test2";
opendir(HAN1, "$DIR") || dir "Problem: $!";
my @array1 = readdir(HAN1);
if("$#array1" > 1) {
for (my $i=0;$i<2 ..="" .="" amp="" are="" array1="" get="" here="" i="" nbsp="" p="" shift="" trimmed=""> # . (present directory) and .. (parent Directory)
MailNewFiles(@array1);
} else { print "No New Files!\n"; }}
}
sub MailNewFiles {
use Mail::Mailer;
my $from = "root";
my $to = "root";
my $subject = "New files";
my $mailer = Mail::Mailer->new();
$mailer->open({ From => $from,
To => $to,
Subject => $subject,
});
my $header = "New Files";
print $mailer $#_ + 1;   # _ Array values (Total Number of Values in Array )
print $mailer "$header\n";
foreach (@_) { print $mailer "$_\n";}
}


### DATABASE I
NOTE: When we need VARIABLE Interpolation..we should use "" (double quotes)..if we don't
want to have variable interpolation ('') single quotes

NOTE: Easiest way to return values is to store them in an array and for looping ...

Example:
#!/usr/bin/perl
use warnings;
use strict;
use DBI;
#Step1 - create connection objection
my $dsn = 'DBI:mysql:contacts';
my $user = 'linuxtutorialperl';
my $password = 'abc123';
my $conn = DBI->connect($dsn,$user,$password) || die "Error connecting" . DB$
$Step2 - define Query
my $query1 = $conn->prepare('SELECT * FROM addressbook') || die "Error prep$
#Step3 - execute query
$query1->execute || die "Error executing query" . $query->errstr;
#step4 - return results
my @results;
while (@results = $query1->fetchrow_array()) {
# my $firstname = $results[0];
# print "$firstname", "\n";
foreach(@results) {
print "$_", "\n";    ## _ is a magical variable..perl provides
}
}
if ($query1->rows == 0) {
print "No Records", "\n";
}
NOTE:
"do" is a shortcut to insert/update/delete

Example:
#!/usr/bin/perl
use warnings;
use strict;
use DBI;
my $dsn = 'DBI:mysql:contacts';
my $user = 'linuxtutorialperl';
my $password = 'abc123';
my $conn = DBI->connect($dsn,$user,$password) || die "Error connecting" . DB$
my $firstname = "Gyanio";
my $lastname = "pillala";

#Step2 - INSERT/UPDATE/DELETE queries are shortened to 2 steps
$conn->do("INSERT INTO addressbook(address1,address2) VALUES('$firstname','$lastname')") || die "Error preparing query" . $conn->e$

NOTE: "_" underscore variable will be provided by perl..whenever we are looping through

Example:
my $conn = DBI->connect($dsn,$user,$password) || die "Error connecting" . DB$
open (han1. "dbinsert.txt") || "Error opening file: $!";
my @newrecords = ;

foreach (@newrecords) {
my @columns = split;
my $firstname = $columns[0];
my $lastname = $columns[1];
my $zip = $columns[2];
$conn->do("INSERT INTO addressbook(firstname,lastname,zip)

NOTE: Sometimes 'chomp' is necessary to use.. \n will create some problems.

Example:
my $firstname = "Gyanio";
$conn->do("UPDATE addressbook SET firstname='$firstname' WHERE firstname='Gyani'") || die
"Error preparing query" . $conn->errstr;

$conn->do("DELETE FROM addressbook WHERE firstname='George'") || die "Error preparing query" . $conn->errstr;



Example: Connection to remote server
my $dsn2 = 'DBI:mysql:192.168.1.104:linuxtutorialcontacts';   // to remote server


#### PERL REFERENCES EXAMPLE ###### 

#!/usr/bin/perl

my $scalar_val = " Reference test";
my $ref_scalar_val = \$scalar_val;

print "Scalar variable data:", $scalar_val , "\n";
print "ref_scalar_var:", $ref_scalar_val , "\n";
print "Value from Referencedata ", ${$ref_scalar_val} , "\n";

my @array = (1,2,3,4,5,6);
my $ref_array = \@array;

print "Array data: ", @array , "\n";
print "Ref scalar value: ", $ref_array , "\n";
print "Array data with Ref: ", @{$ref_array} , "\n";
print "Array index value directly :",  $array[0] , "\n";
print "Array index value with reference ", @{$ref_array}[0] , "\n";
print "Array index value with reference with Arrow notation ", $ref_array->[0] , "\n";

#Hash
my %hash = ( apple => "pomme", pear => "poire" );
my $hash_r = \%hash;

print " Hash Reference :", $hash_r , "\n";
print " value of the hash with referce :", %{$hash_r} , "\n";
print "Hash value with reference :", $hash_r->{apple} , "\n";

sub Hello{
          print " This is testing \n";
          # Function definition
}

&Hello();  # function call
#my $ref_function = \&Hello;
#print "Ref Function value::: ", $ref_function , "\n";

==================================================================
#!/usr/bin/perl
sub add_numbers
{
          our $array_ref = shift;
       # print "Array::", @{ $_[0]}, "\n";   ## Scalar magical variable $_
          print "Array_ref:: $array_ref\n";
}
@numbers = (1,2,3,4,5,6);

$function_array_ref = add_numbers(\@numbers);  ## passing the referece to function definit.
print "Array return reference: $function_array_ref\n";

#  This is same as @numbers - @{ $array_ref};
#  $numbers[0] - ${ $array_ref}[0]

print "Array data:", @{$array_ref}, "\n";
print "Array data1:", @$array_ref, "\n";
print "Array single value:", ${$array_ref}[0], "\n";

# Perl built-in variables
# Get all the elements of @numbers array.
#Get a particular elements
#print "Array particular elements: ", ${$_[0]}[0], "\n";

# @$array_ref  # same as @{ $array_ref}
# $$array_ref  # same as $ { $array_ref}


=============================

#!/usr/bin/perl
use strict;

my @array1 = (1..5);

my @array2 = ('a'..'e');
my $test = "hello";
print "Arrays:", @array1,"\n",  @array2 , "\n";
sub firstSub {
          print "Array specail varaible holds data: ", @_ , "\n";
          my ($ref_firstArray, $ref_secondArray)=@_;
  print "The first array is :", @{$ref_firstArray},"\n";
   print "The second array is:", @{$ref_secondArray},"\n";
}

firstSub(\@array1, \@array2, $test, "gyani", "syam");  # function call





======================

#!/usr/bin/perl
# array contains Ip and destination ip

@IP = ('192.168.0.1', '192.168.0.2');

#Array contains the source port and destination port numbers
@PORT = ("5000", "5002");

#sublayers of TCP layer
@TCP = ("Q931", "H225", "H245");

#Common layers are available in a TCP packet
@LAYER = ("ETHERNET", "IP" , \@TCP);

@PKT = ( \@IP, \@PORT, \@LAYER );
#Storing the reference of @PKT array into the scalar variable
$array_ref = \@PKT ;

print "Array :", ${$array_ref}[2], "\n";
print "Array :", $$array_ref[2], "\n";
print "Array:", ${${$array_ref}[2]}[2], "\n";  

# All are same below
#${ $array_ref}[2] is same as $array_ref->[2]
#${ ${$array_ref} [2] } [2] is same as $array_ref->[2]->[2]
#${${${$array_ref}[2]}[2]}[1] is same as $aray_ref->[2]->[2]->[1]
#$array_ref->[2][2][1]

===================================

#!/usr/bin/perl
# Create a scalar value.
my $a_scalar = "Some text.";

# Create an array
my @an_array = ('apple', 'orange', 'cherry');

# Create a hash
my %a_hash = (
          'animal' => 'bear',
          'plant' => 'oak',
          'fungus' => 'truffle',
);

# Reference to a scalar
my $scalar_ref = \$a_scalar;

# Reference to an array
my $array_ref = \@an_array;

# Reference to a hash
my $hash_ref = \%a_hash;

# Print scalar value
print $a_scalar, "\n";

# Print scalar value using reference
print $$scalar_ref, "\n";

# Print scalar value
print $an_array[0], "\n";

# Print array value using reference
print $array_ref->[0], "\n";

# Print hash value
print $a_hash{'plant'}, "\n";

# Print hash value using reference
print $hash_ref->{'plant'}, "\n";


================================

#!/usr/bin/perl
#Array of arrays

my @a_array = (
          [1,2,3],
          ['hello', 'there'],
          ['foxtrot', 'tango', 'waltz'],
);

print $a_array[1][0];
print $a_array[2][2];


=======================

#!/usr/bin/perl

#array of hashes

my @a_array = (
          { 1 => 'one', 2 => 'two', 3 => 'three' },
          { 'fox' => 'animal', 'chalk' => 'mineral'},
);

print $a_array[1]->{'fox'};

======================================
#!/usr/bin/perl

use strict;
use warnings;

# A subroutine that prints
# An array

sub print_array
{
#Expect to be passed a reference
# to an array
my $array_ref = shift;
print "Array ref :", $array_ref , "\n";
print "ONly Apple: ", @$array_ref[0] , "\n";
print "ONly Apple: ", ${$array_ref}[0] , "\n";
print "ONly Apple: ", $array_ref->[0] , "\n";
>print "ONly Apple: ", $$array_ref[0] , "\n";

# print each value of the array
# NOte that we typecast the reference
# to an actual array by prefixing it
# with @.
#foreach my $value(@$array_ref) {
##     print "$value", "\n";
#}
}
sub main
{
          # Declare and initialize an array
          my @fruits = ('apple', 'orange', 'banana');
          # pass a reference to the array to a function
          print_array(\@fruits);

}
main();


===================================

#!/usr/bin/perl
use strict;
use warnings;

# A subroutine that returns a hash.
sub get_hash
{
          # Create a hash
          my %a_hash = (
                   1 => 'one',
                   2 => 'two',
                   3 => 'three',
          );
         
          # Return a reference to the hash.
          return \%a_hash;
}

sub main
{
          # Get a reference to a hash.
          my $hash_ref = get_hash();
         
          # Iterate through the hash and print the key-value pairs
          while( my ($key, $value) = each %$hash_ref ) {
                   print "$key = $value\n";
          }
}

main();

======================
#!/usr/bin/perl
use strict;
use warnings;

# A subroutine that writes to a file handle. The file handle is passed in as a reference
sub write_to_file
{
          my $file_ref = shift;
        print " file Reference :: ", $file_ref;
         
          print $file_ref "Hello there";
}


sub main
{
          my $file = "temp.txt";

          # Create a file.
          unless(open FILE, '>>'.$file) {
                   die "\nCannot create '$file'\n";
          }
         
          # Pass a reference to the file handle
          # to a subroutine.
          write_to_file(*FILE);
         
          close FILE;
}

main();

===========================
#!/usr/bin/perl
 my $file = "/etc/passwd";

        # Create a file.
        unless(open PERL_FILE_HANDLE, $file) {
                die "\nCannot create '$file'\n";
        }
#my $val="hello i am variable";
#print PERL_LEARN "I would like to append the data\n";
#print PERL_LEARN "$val";

my $read_first_line = ;
print "First line: ", $read_first_line ;
close(PERL_FILE_HANDLE);

=================

#!/usr/bin/perl
use strict;
use warnings;

sub test {
          print "hello\n";
}

sub main {

          my $text = 'a string';
         
          my $ref1 = \&test;
          my $ref2 = \$text;
          my $ref3 = ['an', 'array'];
          my $ref4 = { 'a' => 'hash' };
          my $ref5 = \*STDIN;
         
          print ref($ref1), "\n";
          print ref($ref2), "\n";
          print ref($ref3), "\n";
          print ref($ref4), "\n";
          print ref($ref5), "\n";
}

main();


No comments: