Jun 22, 2008

Array in Perl

Array:

Its a sequenced list of elements.
Array index starts with zero.

use strict;
use warnings;
use Data::Dumper;

my @arr = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Print Array Values just like that : @arr";

print "\n\n Print Array Values with Dumper : " . Dumper(\@arr);


my @num_arr = qw/100 200 300/;

print "\n First Val : " . $num_arr[0];

print "\n";

Outout :

 Print Array Values just like that : Mother Teresa Abraham Lincoln Winston Churchill Mahathma Gandhi

 Print Array Values with Dumper : $VAR1 = [
          'Mother Teresa',
          'Abraham Lincoln',
          'Winston Churchill',
          'Mahathma Gandhi'
        ];

 First Val : 100
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Scalar

Scalar : 

In Perl, scalar can store a single value at any time.
In the following example, $str contains a string value.
We can store any single integer, string, float value in a scalar. It's as simple as that.

E.g., $str1 = 100;
        $str2 = 'test';
        $str3 = 300.2;


use strict;
use warnings;
use Data::Dumper;

#In Perl, scalar can store a single value at any time.
#In the following example, $str contains a string value.
#We can store any single integer, string, float value in a scalar. It's as simple as that.


#Integer
my $num = 300;
print "\n Number : " . $num;

#String
my $str = "Alex Perter John Dane";

#Array
my @arr = split(/ /,$str);

print "\n After Split : " . Dumper(\@arr);
  

Output:
 Number : 300
 After Split : $VAR1 = [
          'Alex',
          'Perter',
          'John',
          'Dane'
        ];


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Get unique elements from string

#!F:\Perl\bin\perl -w
use strict;
use Data::Dumper;
my $abc = "prabhath vamsi vamsi eswar sandhya vinayaka ";

my @arr = split /\s+/, $abc;
my %uniq = map { $_, 1} @arr;
my @final = keys %uniq;
print Dumper(\@final)

map

1)
$str = "2-5,3-9,1-2,8-1,4-7,5-9,20-3,16-9";
@array=split(/,/, $str);
my @a1= (map
{
($left,$right)=split(/-/,$_);
$left*$right;
}
@array
);
print join(",",@a1),"\n";

2)
@array = (20, 3, 1, 9, 100, 88, 75);
my @new_array = (map { $_*2; } @array);
print join(",", @new_array), "\n";

reverse keyword

#!F:\Perl\bin\perl -w
use strict;

my $a=9;
print "Before Reverse:\n", (1..$a);
print "\nAfter Reverse:\n", reverse (1 .. $a);

Get unique keys from different hashes

- As we konw, keys in a hash are unique, but not the values.

#!F:\Perl\bin\perl -w
use Data::Dumper;
use strict;

#Get unique keys from different hashes
my %hash1 = (a=>10,b=>20,c=>30);
my %hash2 = (a1=>10,b1=>20,c1=>30);
my %hash3 = (a=>10,b=>20,c=>30);
my %uniq_hash;
for my $each (keys(%hash1), keys(%hash2), keys(%hash3)) {
$uniq_hash{$each}++;
}
print "\n", $_ for (keys %uniq_hash),"\n";

Get unique elemenets from Arrays

#!F:\Perl\bin\perl -w
use Data::Dumper;
use strict;

#unique elements from different arrays
my @array1 = (10,20,30);
my @array2 = (11,22,33);
my @array3 = (10,20,30);
my %uniq_arr;

for my $each (@array2, @array3, @array1) {
$uniq_arr{$each}++;
}
print "\n", $_ for (keys %uniq_arr),"\n";

' tr ' or ' y '

Removing the duplicate characters from the string:

#!F:\Perl\bin\perl -w
use strict;


#Removing the duplicate characters ('c' , 'd') but not ('e') from the string
my $val = 'abcccdddddeeeeeeeeeeeeecccccc';
print "\n Given String:", $val;

$val =~ y/cd//s; # 'y' is nothing but 'tr'

print "\nAfter :$val\n";

Defining a undefined variable

If a variable is not defined, we can define like this instead of IF block.

#!F:\Perl\bin\perl
use strict;
use warnings;

# Very simple and easy to use
$a;
$a |= "prabhath";
print "\n Value is:", $a;


=cut
We can avoid the unnecessary if and defined code

$a = 'vamsi';
if ( not defined $a) {
$a = 'prabhath';
}
=cut

substitute for n'th occurance

#!F:\Perl\bin\perl -w
use strict;

# Substitue 3rd occurance of 'perl' with 'PERL'
my $text = 'perl is good, perl is better, perl is best';
print "\n INPUT Text:", $text;

my $nth_occurance = 3;
my $count=0;

$text =~ s{(perl)}{
++$count == $nth_occurance ? 'PERL' : $1
}ige;

print "\n OUTPUT Text:", $text,"\n";

Sort an Array

1) For number Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (20,10,50,40,30); #Unsorted Number Array
print "\n Unsorted Array is: @array";
my @sorted = sort { $a <=> $b } @array;

# '<=>' for numbers only
# 'cmp' used for numbers as well as strings
print "\n sorted Array is: @sorted";
my @sorted = sort { $a cmp $b } @array;

print "\n sorted Array is: @sorted";


2) For String Array

#!F:\Perl\bin\perl -w
use Data::Dumper;
#Unsorted String Array
my @array = qw/sandhya eswar prabhath vamsi/;
print "\n Unsorted Array is: @array";

my @sorted = sort { $a cmp $b } @array;

# 'cmp' can be used for both strings as well as numbers
print "\n sorted Array is: @sorted";

Slurp

- Slurp means reading or writing a file at one shot, instead of
reading or writing line by line.
- Generally slurp if very fast than normal reading a file line by line
- But slurp uses more memory, as it needs to keep th whole file
in a scalar (or) an array, but now a days as everybody is
having enormous amount of hard disk space and RAM, its not
a problem with Slurp.
- But those people where memeory and space concerns are there,
don't go for Slurp
- Some Cpan modules on Slurp are:
1) Slurp # Allows you to read multiple files at a time
2) File::Slurp # Good module for Slurp
3) Perl6::Slurp # Recent module on Slurp with lot more features


The Program will read a folder and read all the files and slurp them into an array and writes to output file
-------------------------------
#!F:\Perl\bin\perl -w

use Slurp;
use File::Slurp;
use Data::Dumper;
use strict;

my $dir='F:\Documents and Settings\Administrator\Desktop\sample_programs';
opendir DIR, $dir or die "cannot open dir $dir: $!";
my @file= readdir DIR;
closedir DIR;

my @final_files;
print "\n All file names before:", Dumper(\@file);

for (@file) {
next if($_ =~/^\.+|\.swp$|\~$/ig);
push (@final_files, $_);
}

my @zx = slurp(@final_files);
write_file('output.txt', @zx);

my @out = File::Slurp::read_file('output.txt');
print "\n output:" , Dumper(\@out);

Get a Random element from an Array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array = (10,20,30,40,50);
#'rand' gives some random index number
$index = rand @array;
print "\n Random index from an array is:", $index;
$element = $array[$index];
print "\n Random element from an array is:", $element,"\n";

While loop in Perl

We can loop through For/Foreach/While in Perl.

We can discuss while loop now with the following example.



use strict;
use warnings;
use Data::Dumper;

my @names = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Looping While using counter";

my $i=0;

print "\n Scalar Array Size " . scalar(@names) . "\n";

while ($i <= $#names) {
   print "\n Looping ... " . $names[$i] . "\n";
   $i++;
}

print "\n";
  

Output :
 Looping While using counter
 Scalar Array Size 4

 Looping ... Mother Teresa

 Looping ... Abraham Lincoln

 Looping ... Winston Churchill

 Looping ... Mahathma Gandhi
 


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Example on Greedy Operator ' * '

#!F:\Perl\bin\perl -w
use strict;

my $str = "perl is awesome, I am also awesome";
$str =~ /.*awesome/; # '*' is greedy operator, so it is not satisfied with the first occurance
print $&,"\n"; # perl is awesome, I am also awesome

#To restict the greeedyness to first occurance
#Use '?' operator to restrict the greediness
$str =~ /.*?awesome/;
print $&,"\n"; #perl is awesome

$^O gives the OS name

#!F:\Perl\bin\perl -w
use strict;
print "$^0\n";

Different ways to remove duplicates from array

#!F:\Perl\bin\perl -w
use strict;
use Data::Dumper;

#Remove duplicates from array.
my @array = qw/10 20 20 20 30 40 40 40 50 50 50/;
print "\n Duplicate array: @array";

1) Good

my %hash;
$hash{$_} = 0 for (@array);
# $hash{$_} = () for (@array); #You can do this also

my @final = keys (%hash);
print "\n Unique Array: @final";
print "\n";


2) Best of all

my %hash = map { $_ , 1 } @array;
my @uniq = keys %hash;
print "\n Uniq Array:", Dumper(\@uniq);


3) Costly process as it involves 'greping'

my %saw;
my @out = grep(!$saw{$_}++, @array);
print "\n Uniq Array: @out \n";

How to create an unique array

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array_with_duplicate_elements = qw/ 1 2 3 4 5 5 5 5 4 4 4/;
my %hash = map { $_, 1 } @array_with_duplicate_elements;
my @unique_array = keys %hash;
print Dumper(\@unique_array);

Hash in Perl

Hashes are like named key value pairs.
Keys are always unique, Values can be anything.
It's best practice to use hashes, they are efficient.

 

use strict;
use warnings;
use Data::Dumper;

my %hash = (a => 10,
            e => 40,
            c => 30,
            d => 40,
            b => 20,
            a => 100);

#Print Keys
print "\n Only Keys:\n" . Dumper(keys %hash);

print "\n\n";
#Print Values
print "\n Only Values:\n" . Dumper(values %hash);


print "\n\n";
#Print Keys and Values
while ( my ($key, $value) = each %hash)
{
   print "$key => $value\n";
}

print "\n\n";



#Print Keys
print "\n Sorted Keys:\n" . Dumper(sort keys %hash);

print "\n\n";
#Print Values
print "\n Sorted Values:\n" . Dumper(sort values %hash);
  
Output:

 Only Keys:
$VAR1 = 'e';
$VAR2 = 'c';
$VAR3 = 'a';
$VAR4 = 'b';
$VAR5 = 'd';



 Only Values:
$VAR1 = 40;
$VAR2 = 30;
$VAR3 = 100;
$VAR4 = 20;
$VAR5 = 40;


e => 40
c => 30
a => 100
b => 20
d => 40



 Sorted Keys:
$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';
$VAR4 = 'd';
$VAR5 = 'e';



 Sorted Values:
$VAR1 = 100;
$VAR2 = 20;
$VAR3 = 30;
$VAR4 = 40;
$VAR5 = 40;
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Formatted Print

#!F:\Perl\bin\perl -w
use strict;

printf("\n%.2f", 19.9500000000000000000);
printf("\n%.3f", 19.9500000000000000000);

How to get all files in a directory

#!F:\Perl\bin\perl -w
use strict;

opendir(DIR, ".");
my @files = readdir(DIR);
closedir(DIR);
foreach my $file (@files) {
print "$file\n";
}

Count no.of digits in a string

#!F:\Perl\bin\perl -w
use strict;

my($test,$number);
$test = "12344tyyyyy456";
$number = ($test =~ tr/[0-9]/[0-9]/);
print "Number of digits in variable is : $number ";

How to reverse hash or Lookup a hash by value instead of key

But remember keys are uniue but values are not, so before reversinf the
original array values should be unique, after reverse these values become
keys of reversed array. Otherwise things will not work out in ur way.
Anyways just give a try
# Eg: %hash = ( a => 10, b => 10, c => 10, d => 10);

Example1:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is good and easy to use but not tat much efficient in terms of space,
as it needs to keep a copy of the hash.

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);

%reverse = reverse %hash; # It will reverse the hash

print "\n Hash after reverse :", Dumper(\%reverse);
print "\n";


Example2:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is sapce efficient

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);
while (($key, $value) = each %hash) {
$hash{$value} = $key;
}
print "\n Hash after reverse :", Dumper(\%hash);
print "\n";

How to use upper case (or) lower case

#!F:\Perl\bin\perl -w
use strict;

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text = uc $text; # To make $text to upper case
print "\n After :", $text,"\n";

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text = lc $text; # To make $text to lower case
print "\n After :", $text,"\n";

Make first letter of every word in a string to Upper case

#!F:\Perl\bin\perl -w
use strict;

my $text = 'india is a great country';
print "\n Before:", $text; # india is a great country
$text =~ s/(\w+)/\u$1/g; # \u option is used
print "\n After :", $text,"\n"; # India Is A Great Country

use of $_

#!F:\Perl\bin\perl -w
use strict;

1) print "\n", $_ for (1..10);

2)
my %hash = ( a => 100, b => 200, c => 300);
print "\n", $_ for keys(%hash);:

count no. of occurances of a word

Example1 :
#########

#!F:\Perl\bin\perl -w
use strict;

my $text = 'perl is good, perl is better, perl is best';
my $count = ($text =~ s/perl/perl/g);
print "\n No. of occurances of 'perl' is:", $count;
print "\n";


Example2 :
#########

#!F:\Perl\bin\perl -w
use strict;

my $p = "india s great country india india super";
my $find = "india";
my $count = () = $p =~ /$find/g;
print "\n Count:", $count;
print "\n";


Example3:
########

use strict;
my($test,$number);
$test = "12344tyyyyy456";
$number = ($test =~ tr/[0-9]/[0-9]/);
print "Number of digits in variable is :- $number ";

Find difference, union and intersection of two arrays

#!F:\Perl\bin\perl -w

use Data::Dumper;
@union = @intersection = @difference = ();
%count = ();

#Make sure that both arrays are unique
my @array1 = (10, 20, 30, 40, 50, 60);
my @array2 = (50, 60, 70, 80, 90, 100);

foreach $element (@array1, @array2) { $count{$element}++ }

#print "\n all values hash:", Dumper(\%count);

foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}


print "\n Union values:", Dumper(\@union);
print "\n Intersection Values:", Dumper(\@intersection);
print "\n Difference Array:", Dumper(\@difference);
print "\n";

compare two arrays

#!F:\Perl\bin\perl -w
use Data::Dumper;

my @array1 = ('a','b','c','d','e');
my @array2 = ('a','b','c','d','e');

if ( @array1 == @array2) {
print "\n equal";
} else {
print "\n not equal";
}

Closure in Perl

What is closure?

- Anonymous subroutines (subroutines without name) act as closures with respect to my() variables ie., lexical variables.

- Closure says if you define an anonymous function in a particular lexical
context, it pretends to run in that context even when it's called outside of
the context.

Example:
########

#!F:\Perl\bin\perl -w
use strict;

sub newprint {
   my $x = shift; # 'x' is a lexical variable
   return sub { my $y = shift; print "$x, $y!\n"; }; #Anonymous subroutine, observe $x
}
my $h = newprint("Howdy");
my $g = newprint("Greetings");

&$h("world"); # Howdy world
&$g("earthlings"); # Greetings earthlings


Note particularly that $x continues to refer to the value passed into
newprint() despite the fact that the my $x has seemingly gone out of
scope by the time the anonymous subroutine runs. That's what closure is all
about.

This applies only to lexical variables, by the way. Dynamic variables
continue to work as they have always worked. Closure is not something that
most Perl programmers need trouble themselves about to begin with.


One More Example on Closure:
##########################

- The important thing about closures is that you can use them to hide different lexicals into seperate
references to the same subroutine.

- I think that the important thing about closures is being able to call the same code but have it use different
variables (without passing them in as arguments).


use strict;
sub make_hello_printer {
  my $message = "Hello, world!";
  return sub { print $message; }
}

my $print_hello = make_hello_printer();
$print_hello->()



As you'd expect, that prints out the Hello, world! message. Nothing special going on here, is there? Well,

actually, there is. This is a closure. Did you notice?

What's special is that the subroutine reference we created refers to a lexical variable called $message. The

lexical is defined in make_hello_printer, so by rights, it shouldn't be visible outside of make_hello_printer,

right? We call make_hello_printer, $message gets created, we return the subroutine reference, and then

$message goes away, out of scope.

Except it doesn't. When we call our subroutine reference, outside of make_hello_printer, it can still see and

receive the correct value of $message. The subroutine reference forms a closure, ``enclosing'' the lexical

variables it refers to.


One More Example on Closure:
##########################

#!F:\Perl\bin\perl -w
use strict;

sub make_counter {
my $start = shift;
return sub { $start++ }
}

my $from_ten = make_counter(10);
my $from_three = make_counter(3);
print $\ = "\n"; # Prints new line each and every print
print $from_ten->(); # 10
print $from_ten->(); # 11
print $from_three->(); # 3
print $from_ten->(); # 12
print $from_three->(); # 4

How to use Ciel and Floor Functions

#!F:\Perl\bin\perl -w
use strict;

use POSIX; #ciel and floor available in POSIX module

$a = ceil(3.45);
print "\n $a"; #gives o/p as '4'

$b = floor(3.45);
print "\n $b"; #gives o/p as '3'

printf("\n%.3f", 3.1415926535); #gives output as 3.142, rounds of to 3 digits
#For Rounding use printf and sprintf

Different ways of calling a method

a) We are calling the method after the definition

#!F:\Perl\bin\perl -w
use strict;

sub method {
print " \n Inside the method";
}

method; #Works as you expect
&method #Works as you expect, '&' is the general way of calling a method
method(); #Works as you expect since 'method' is not taking any parameters


b) We are calling the method before the definition itself

#!F:\Perl\bin\perl -w
use strict;

method; #Error
&method #Works as you expect, '&' is the general way of calling a method
method(); #Works as you expect since 'method' is not taking any parameters

sub method {
print " \n Inside the method";
}


So before the definition of a function if you call the function,you hav to compulsarily use either '()' [Eg: method()] or '&' [Eg: &method]

Difference between array and array reference

#!F:\Perl\bin\perl -w
use strict;

my $array = [ qw/sandhya prabhath eswar vamsi/];
print $array[0]; # Throws error since $array is a reference, you can't accesss directly
print $array->[0]; # sandhya

my @arr = qw/ 100 200 300/;
print $arr[0]; # Now you cn access as usual, since it is an array

How to call anonymous sub-routine

#!F:\Perl\bin\perl -w
use strict;

#This is called anonymous subroutine , since no name is given to that.
my $hello = sub { print "Helloooooo" };
print $hello->();

shebang line

- She-bang line is nothing but the path where the perl interpreter is there.
- It should start with #!
- It should be the starting line of your program
- E.g.,
In Linux Environment use like this:#! /usr/bin/perl

In Windows Environment use like this:#! C:\Perl\bin\perl