Вы находитесь на странице: 1из 12

The difference between single quotes and double quotes is that single quotes

mean that their contents should be taken literally, while double quotes mean
that their contents should be interpreted. For example, the character
sequence \n is a newline character when it appears in a string with double
quotes, but is literally the two characters, backslash and n, when it appears
in single quotes.

print "This string\n shows up on two lines.";

print 'This string \n shows up on only one.';

Scalar ($) variable:

 Scalar variable allows us to store one thing which is scalar.


 It could be a string or a number.

Array (@) Variable:

 Array variable allows us to store a collection of scalar.


 We can access each scalar data in array by using indices.
 An array can hold as many as scalar as we want depends on available
memory of our computer. Accessing an element of array often involves
sequential access until we find what we need.

Hash (%):

 When number of item in an array is bigger, the performance is degraded


also. Perl created hash - before that it is called associative array -
to overcome this limitation.
 Hash is another kind of collective data type. Hash can hold as many as
scalar like array but the way we accessing hash element is different.
 We access hash element in hash by using a “key”. 
 Each hash element has two parts: key and value or key-value pair.
 The key identifies the value of element associated with it. To define a
hash variable, we use percentage sign (%).

Accessing Hash elements


To access a hash element, you use the key of that element to retrieve the
value as follows:

print $websites{"perltutorial.org"}; #Perl tutorial

The code snippet prints values associated with key "perltutorial.org". The
dollar sign ($) is used instead of percentage sign (%) because hash element is
scalar. Curly braces is used surrounded within hash key instead of square
bracket in array.
What purpose does each of the following serve: -w, strict, -T ?
-W
This very important switch tells Perl to produce extra warning messages about
potentially dangerous constructs.

Scalar ($) variables


Scalar variables are simple variables containing only one element--a string, a number, or a
reference. Scalar variables are that they contain only one single piece of data.
Strings => It contains any symbols, letters, or numbers
 There is no limit to the size of the string, any amount of characters, symbols, or words can
make up your strings.
 When defining a string you may use single or double quotations, you may also define them
with the q subfunction.
Numbers => It contains real numbers, float, integers, exponents, octal, and hexadecimal numbers.
Examples:
$number = 5;
$real = 3.14159;
$integer = -4;
$exponent = "2 ** 8";
$exponent = 10e12;
$string = "Hello, Perl!";
$single = 'This string is single quoted';

Array (@) variables


In Perl, arrays are defined with the (@) symbol.
 Arrays contain a list of scalar data (single elements).
 A list can hold an unlimited number of elements.
 List elements can either be a string, a number, or any type of scalar data including another
variable.
Examples:
@days = ("Monday", "Tuesday", "Wednesday");
@months = ("April", "May", "June");

#!/usr/bin/perl

# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# PRINT THE ARRAY


print "@coins";
print "\n";
print @coins

Note: We printed the same array twice using quotes around the first line. PERL does this automatically as
it assumes the quotations are meant for a string and strings are usually comprised of words that require
spacing between each word.
Array indexing
Each element of the array can be indexed using a scalar ($) version of the same array. When an array is
defined, PERL automatically numbers each element in the array beginning with zero.
Example:
#!/usr/bin/perl

# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# PRINT THE WHOLE ARRAY


print "@coins";

# PRINT EACH SCALAR ELEMENT


print $coins[0]; #Prints the first element
print "\n";
print $coins[1]; #Prints the 2nd element
print "\n";
print $coins[2]; #Prints the 3rd element

Note: Elements can also be indexed backwards using negative integers instead of positive numbers.

The “qw” subroutine


Quotations can be a hassle, especially if the array we wish to build has more than 5 elements. Use this
neat little subroutine to remove the need for quotes around each element when we define an array.
Example:
#!/usr/bin/perl

# DEFINE AN ARRAY WITHOUT QUOTES


@coins = qw(Quarter Dime Nickel);
print "@coins";

Sequential number arrays


PERL offers a shortcut for sequential numbers and letters. Rather than typing out each element when
counting to 100 for example.
Example:
#!/usr/bin/perl

# SHORTCUTS SAVE TIME


@10 = (1 .. 10);
@100 = (1 .. 100);
@1000 = (100 .. 1000);
@abc = (a .. z);

# PRINT 'EM TO THE BROWSER


print "@10\n";
print "@100\n";
print "@1000\n";
print "@abc\n";

Finding the length of an array


Retrieving a numerical value that represents the length of an array is a two-step process. First, you need
to set the array to a scalar variable, and then just print the new variable.
There are two ways to set an array to scalar mode. We can use the scalar () function or we can redefine
the array as a scalar variable
Example:
#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

@nums = (1 .. 20);
@alpha = ("a" .. "z");

# SCALAR FUNCTION
print scalar(@nums)."\n";
print scalar(@alpha)."\n";

# REDEFINE TO SCALAR
$nums = @nums;
$alpha = @alpha;

print "$nums\n";
print "$alpha\n";

Adding and removing elements


Adding elements is a breeze, we use the following functions to add/remove and elements:
 push() - adds an element to the end of an array.
 unshift() - adds an element to the beginning of an array.
 pop() - removes the last element of an array.
 shift() - removes the first element of an array.
When adding elements using push() or unshift() you must specify two arguments, first the array name and
second the name of the element to add. Removing an element with pop() or shift() only requires that you
send the array as an argument.
Example:
#!/usr/bin/perl

# AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# ADD ELEMENTS
push(@coins, "Penny");
print "@coins";
print "\n";
unshift(@coins, "Dollar");
print "@coins";

# REMOVE ELEMENTS
pop(@coins);
print "\n";
print "@coins";
shift(@coins);
print "\n";

# BACK TO HOW IT WAS


print "@coins";
Array Functions:
Function Definition
push(@array, Element) Adds to the end of an array
pop(@array) Removes the last element of the array
unshift(@array, Element) Adds to the beginning of an array
shift(@array) Removes the first element of an array
delete $array[index] Removes an element by index number

Define a hash (%)


Hashes are complex lists with both a key and a value part for each element of the list.
We define a hash using the percent symbol (%).
Example:
%coins = ("Quarter", 25, "Dime", 10, "Nickle", 5);
%ages = ("Jerry", 45, "Tom", 22, "Vickie", 38);

Q. How do I do < fill-in-the-blank > for each element in a hash?


Here's a simple technique to process each element in a hash:

#!/usr/bin/perl -w

%days = (
'Sun' =>'Sunday',
'Mon' => 'Monday',
'Tue' => 'Tuesday',
'Wed' => 'Wednesday',
'Thu' => 'Thursday',
'Fri' => 'Friday',
'Sat' => 'Saturday' );
foreach $key (sort keys %days) {
print "The long name for $key is $days{$key}.\n";
}

Q. How do I sort a hash by the hash key?


Suppose we have a class of five students. 
Their names are kim, al, rocky, chrisy, and jane.

Here's a test program that prints the contents of the grades hash, sorted by
student name:

#!/usr/bin/perl –w

%grades = (
Kim=>96,
al=>63,
rocky=>87,
chrisy=>96,
jane=>79,
);
print "\n\tGRADES SORTED BY STUDENT NAME:\n";
foreach $key (sort (keys(%grades))) {
print "\t\t$key \t\t$grades{$key}\n";
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:

al 63
chrisy 96
jane 79
kim 96
rocky 8

Q. Find out a Min and Max Number


This is only efficient up to about 250 values in @ar, if @ar is going to have more values
than that you should use the min and max functions from [List::Util][0] (note List::Util has
been part of core Perl since version 5.8 and is available on CPAN for earlier versions):

#!/usr/bin/perl

use strict;
use warnings;

use List::Util qw/max min/;


use List::Util qw/maxstr minstr/;

my @num = (1,2,3,4,58,9,2,1);
my @str = qw/a f d s e z s f t/;
my $max = max @num;
my $min = min @num;
my $maxstr = maxstr @str;
my $minstr = minstr @str;
print "max $max min $min maxstr $maxstr minstr $minstr\n";

Q. Why we should 'use strict'?


We should be starting every Perl program with these lines:

#!/usr/local/bin/perl –w
use strict;
This will help us (really, it will force us) to write better, cleaner code.
Adding the -w switch to the perl interpreter will cause it to split out
warnings on uninitialized variables - potential bugs.
‘use strict’ does two things:
 It makes us to declare all our variables (``strict vars'')
 It makes it harder for Perl to mistake our intentions when we are using
subs (``strict subs'')

 'use strict' turns on the 'strict' pragma which will make us declare our


variables with the “my” keyword.
 'use strict' also tosses up errors if our code contains any bare words
that can't be interpreted in their current context. 

use strict 'vars'; # We want to require variables to be declared

no strict 'vars'; # We'll go back to normal variable rules now

use strict 'subs'; # We want Perl to distrust barewords (see below).

no strict; # Turn it off. Turn it all off. Go away, strict.

Strict vars:

One way to make our programs more correct is to use strict vars, which means
that we must always declare variables before we use them. We declare variables
by using the “my” keyword, either when we assign values to them or before we
first mention them:

my ($i, $j, @locations);


my $filename = "./logfile.txt";
$i = 5;

use strict;
my $i = 5; # Or "my ($i); $i = 5;", if you prefer...
print "The value is $i.\n"

Question: What elements of the Perl language could you use to structure your code to allow for
maximum re-use and maximum readability?

Answer: modules
The element is keyword "sub" means write the subroutines, which allow maximum
readability and allow maximum-reuse

if want any other;write the classes and package.

Questions: What are the characteristics of a project that is well suited to Perl?

Answer: For writing exploits, testing products and apps, identifying new Web-based vulnerabilities, and
creating complex regular-expression engines.
Question: Explain the difference between my and local ?

Answer: The variables declared with my() are visible only within the scope of the block it was defined. It
is visible outside of this block, not even in routines or blocks that it calls.

local() variables, on the other hand, are visible to routines that are called from the block where they are
declared. Neither is visible after the end (the final closing curly brace) of the block at all.

Question: Explain the difference between use and require ?

Answer:
require:
 The “require” keyword imports the functions and objects only within
their defined packages.
 The included objects are verified at the run time.
 The method is used for both libraries and modules.
 Need to give file Extension.
use:
 The “use” keyword, imports the functions and objects so they are
available to the current package as if they had been defined globally.
 The included objects are verified at the time of compilation.
 The method is used only for the modules
 No Need to give file extension.

For example,

require Cwd;
$pwd = Cwd::getcwd();

as opposed to

use Cwd;
$pwd = getcwd();

“use” statements are interpreted and executed at the time the file is parsed,
but require statements import modules at run time, which means you can supply
a variable name to a require statement based on other elements of your
program.

Question: How to assign an empty list in a fastest way ?


Answer: my %hash = ();
 
Question: How to initialize a hash reference ?
Answer:You can use my alone, or you can assign a value
             my $hash_ref;
             my $hash_ref = 0; # zero
 
Question: How to add a key/value pair to the hash ?
Answer:
             $hash{ 'key' } = 'value'; # hash
             $hash{ $key } = $value; # hash, using variables
 
Question: How to add several key values pairs to hash ?
Answer: Both are equal but second one is more reliable
 
%hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3' );

%hash = (
key1 => 'value1',
key2 => 'value2',
key3 => 'value3',
);
 
Question:How to copy a hash ?
Answer:
my %hash_copy = %hash; # copy a hash
my $href_copy = $href; # copy a hash ref
 
Question: How to delete a single key/value pair ?
Answer:
Following deletes a Hash
delete $hash{$key};
 
Following deletes a Has reference
delete $hash_ref->{$key};
 
Question: How to perform an action on each key/value pair in the hash ?
Answer: Use each within a while loop. Note that each iterates over entries in an apparently random order,
but that order is guaranteed to be the same for the functions keys and values
 
while ( my ($key, $value) = each(%hash) ) {
print "$key => $value\n";
}
 
A hash reference would be only slightly different:
 
while ( my ($key, $value) = each(%$hash_ref) ) {
print "$key => $value\n";
}
 
Question: How to use keys in a for LOOP ?
Answer:
for my $key ( keys %hash ) {
my $value = $hash{$key};
print "$key => $value\n";
}
 
Example using While and For LOOP
 
my $file = $ARGV[0] || "-";

my %from = ();

open FILE, "< $file" or die "Can't open $file : $!";

while( ) {
if (/^From: (.*)/) { $from{$1}++ } # count recurrences of sender
}
close FILE;

for my $sender ( sort keys %from ) {


print "$sender: $from{$sender}\n";
}
 
Question: How to get the size of a hash ?
Answer: print "size of hash: " . keys( %hash ) . ".\n";
 
my $i = 0;

$i += scalar keys %$hash_ref; # method 1: explicit scalar context


$i += keys %$hash_ref; # method 2: implicit scalar context
 
Question: How to use Hash references ?
Answer:
sub foo
{
my $hash_ref;

$hash_ref->{ 'key1' } = 'value1';


$hash_ref->{ 'key2' } = 'value2';
$hash_ref->{ 'key3' } = 'value3';

return $hash_ref;
}

my $hash_ref = foo();

print "the keys... ", sort keys %$hash_ref, "...\n";

Q. What is the difference between for & foreach, exec & system?
Ans:
 Technically, there's no difference between for and foreach other
than some style issues.
 One is an alias of another. We can do things like this

foreach (my $i = 0; $i < 3; ++$i) 


{ # normally this is foreach print $i, "n";}

for my $i (0 .. 2) 
{ # normally this is for print $i, "n";}

 exec runs the given process, switches to its name and never returns

 While system forks off the given process, waits for it to complete and
then returns.

3) What is Grep used for in Perl?

Answer:
 @LIST = grep (EXPRESSION, @ARRAY);
 Perl's grep () function runs a regular expression on each element of an array, and returns only the
elements that evaluate to true.
@myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Alexander', 'Andrew');
@grepNames=grep(/^A/,@myNames);  # @grepNames becomes ('Alexander ', 'Andrew').

Q. How to substitute a particular string in a file containing million of record?


Ans:

perl -p -i bak -e 's/search_str/replace_str/g' filename

-p  Is a named pipe?

-e  Evaluate replacement string as expression

-g change all occurances of the pattern

-i  ignore case in pattern

Or you can write the following code:

--replace.pl--- 

#!/usr/bin/perl 

if(-e $ARGV[0]) 


    $cmd = 'copy $ARGV[0] $ARGV[0].bak'; 

`$cmd`; 

else 

    print 'File does not exist.\n'; 

exit; 

open(INPUT,'$ARGV[0].bak') or die 'Cannot open file: $!\n'; 

open(OUTPUT,'>$ARGV[0]'); 

while(INPUT){ 
    $_ =~ s/$ARGV[1]/$ARGV[2]/g; 

    print $_; 

    print OUTPUT $_; 

close INPUT; 

close OUTPUT;
6) What is it meant by '$_' ?

Answer:

It is a default variable which holds automatically, a list of


arguments passed to the subroutine within parentheses.

5) Wat are the arguments w normally use for Perl interpreter? 

Answer:
-e for execute

-c to compile

-d to call the debugger on the file specified

-T for traint mode for security/input checking

-W for show all warning mode

-w to show less warning

-strict pragma is used when we should declare variables before their


use  

 Q. What is the difference between die and exit in perl?

Ans:

1) die is used to throw an exception (catchable using eval). 


exit is used to exit the process.

2) die will set the error code based on $! or $? if the exception is uncaught. 
exit will set the error code based on its argument.

3) die outputs a message 


exit does not.

Вам также может понравиться