Wednesday, August 5, 2009

Learn perl easy part 1

1)Print a Message to the Terminal


print "When that Aprill with his shoures soote\n";
print "The droghte of March ath perced to the roote,\n";
print "And bathed every veyne in swich licour\n";
print "Of which vertu engendered is the flour...\n";

getting out put:

When that Aprill with his shoures soote
The droghte of March ath perced to the roote,
And bathed every veyne in swich licour
Of which vertu engendered is the flour...

2) math operations

print "2 + 2 =", 2+2, "\n";
print "log(1e23)= ", log(1e23), "\n";
print "2 * sin(3.1414)= ", 2 * sin(3.1414), "\n";

2 + 2 =4
log(1e23)= 52.9594571388631
2 * sin(3.1414)= 0.000385307177203065

Run a System Command
system "ls";

4)Return the Time of Day

$time = localtime;
print "The time is now $time\n"; //even in double codes $time will prints time and day of month


option 1)perl

option 2)vi
#!/usr/bin/perl // add this line at first
# file: // optional
$time = localtime;
print "The time is now $time\n";

#chmod +x

Useful Perl Command-Line Options

You can call Perl with a few command-line options to help catch errors:

-c Perform a syntax check, but don't run.

-w Turn on verbose warnings.

-d Turn on the Perl debugger.

like perl -cw or simply add #!/usr/bin/perl -w line at beginning of the program.


statement is a command that is recognized by the Perl interpreter and executed. Statements are terminated by the semicolon character (;). They are also usually separated by a newline character to enhance readability.

$sum = 2 + 2; # this is a statement

$f = ; $g = $f++; # these are two statements

$g = $f

$sum; # this is one statement, spread across 3 lines


{ # block starts
my $EcoRI = 'GAATTC';
my $sequence = ;
print "Sequence contains an EcoRI site" if $sequence=~/$EcoRI/;
} # block ends

my $sequence2 = ;
if (length($sequence) < length = ",length($sequence),">

Labeled Blocks

You can also attach a label to a block of statements like this:

READ_SEQUENCE: { #this is my lable
$sequence =
print "length = ",length($sequence),"\n";
This is sometimes useful for controlling nested loops.


Literals are constant values that you embed directly in the program code. Perl supports both string literals and numeric literals.

The difference between single and double-quoted strings is that variables and certain special escape codes are interpolated into double quoted strings, but not in single-quoted ones.

\040 Octal character (octal 040 is the space character)
\0x2a Hexadecimal character (hex 2A is the "*" character)
\cA Control character (This is the ^A character)
\u Uppercase next character
\l Lowercase next character
\U Uppercase everything until \E
\L Lowercase everything until \E
\Q Quote non-word characters until \E
\E End \U, \L or \Q operation


"She cried \"Oh dear! The parakeet has flown the coop!\"";
# evaluates to: She cried "Oh dear! The parakeet has flown the coop!"

Numeric Literals

You can refer to numeric values using integers, floating point numbers, scientific notation, hexadecimal notation, and octal. With some help from the Math::Complex module, you can refer to complex numbers as well:

-1.23; # a negative floating point number
1_000_000; # you can use _ to improve readability
1.23E45; # scientific notation
0x7b; # hexadecimal notation (decimal 123)
0173; # octal notation (decimal 123)
use Math::Complex; # bring in the Math::Complex module

12+3*i; # complex number 12 + 3i

Backtick Strings

You can also enclose a string in backtics (`). This has the unusual property of executing whatever is inside the string as a Unix system command, and returning its output:

`ls -l`;
# evaluates to a string containing the output of running the
# ls -l command


The last type of literal that Perl recognizes is the list, which is multiple values strung together using the comma operator (,) and enclosed by parentheses. Lists are closely related to arrays, which we talk about later.

('one', 'two', 'three', 1, 2, 3, 4.2);
# this is 7-member list contains a mixure of strings, integers
# and floats

operators :

Numeric & String Operators.

The "." operator acts on strings. The "!" operator acts on strings and numbers. The rest act on numbers.

Operator Description Example Result
. String concatenate 'Teddy' . 'Bear' TeddyBear
= Assignment $a = 'Teddy' $a variable contains 'Teddy'
+ Addition 3+2 5
- Subtraction 3-2 1
- Negation -2 -2
! Not !1 0
* Multiplication 3*2 6
/ Division 3/2 1.5
% Modulus 3%2 1
** Exponentiation 3**2 9

File input
Read a line of input from standard input
>> Right bit shift 3>>2 0 (binary 11>>2=00)
<< Left bit shift 3<<2 12 (binary 11<<2=1100)
| Bitwise OR 3|2 3 (binary 11|10=11
& Bitwise AND 3&2 2 (binary 11&10=10
^ Bitwise XOR 3^2 1 (binary 11^10=01

Logical Operators

These operators compare strings or numbers, returning TRUE or FALSE:

Numeric Comparison String Comparison
3 == 2 equal to 'Teddy' eq 'Bear' equal to
3 != 2 not equal to 'Teddy' ne 'Bear' not equal to
3 <> less than 'Teddy' lt 'Bear' less than
3 > 2 greater than 'Teddy' gt 'Bear' greater than
3 <= 2 less or equal'Teddy' le 'Bear' less than or equal
3 >= 2 greater than or equal'Teddy' ge 'Bear' greater than or equal
3 <=> 2 compare'Teddy' cmp 'Bear' compare

'Teddy' =~ /Bear/ pattern match

The <=> and cmp operators return:

  • -1 if the left side is less than the right side
  • 0 if the left side equals the right side
  • +1 if the left side is greater than the right side

File Operators

Perl has special file operators that can be used to query the file system. These operators generally return TRUE or FALSE.


print "Is a directory!\n" if -d '/usr/home';
print "File exists!\n" if -e '/usr/home/lstein/test.txt';
print "File is plain text!\n" if -T '/usr/home/lstein/test.txt';

There are many of these operators. Here are some of the most useful ones:

-e filename file exists
-r filename file is readable
-w filename file is writable
-x filename file is executable
-z filename file has zero size
-s filename file has nonzero size (returns size)
-d filename file is a directory
-T filename file is a text file
-B filename file is a binary file
-M filename age of file in days since script launched
-A filename same for access time


In addition to its operators, Perl has many functions. Functions have a human-readable name, such as print and take one or more arguments passed as a list. A function may return no value, a single value (AKA "scalar"), or a list (AKA "array"). You can enclose the argument list in parentheses, or leave the parentheses off.

A few examples:

 # The function is print. Its argument is a string.
# The effect is to print the string to the terminal.
print "The rain in Spain falls mainly on the plain.\n";

# Same thing, with parentheses.
print("The rain in Spain falls mainly on the plain.\n");

# You can pass a list to print. It will print each argument.
# This prints out "The rain in Spain falls 6 times in the plain."
print "The rain in Spain falls ",2*4-2," times in the plain.\n";

# Same thing, but with parentheses.
print ("The rain in Spain falls ",2*4-2," times in the plain.\n");

# The length function calculates the length of a string,
# yielding 45.
length "The rain in Spain falls mainly on the plain.\n";

# The split function splits a string based on a delimiter pattern
# yielding the list ('The','rain in Spain','falls mainly','on the plain.')
split '/','The/rain in Spain/falls mainly/on the plain.';

Often Used Functions (alphabetic listing)

For specific information on a function, use perldoc -f function_name to get a concise summary.

abs absolute value
chdir change current directory
chmod change permissions of file/directory
chomp remove terminal newline from string variable
chop remove last character from string variable
chown change ownership of file/directory
close close a file handle
closedir close a directory handle
cos cosine
defined test whether variable is defined
delete delete a key from a hash
die exit with an error message
each iterate through keys & values of a hash
eof test a filehandle for end of file
eval evaluate a string as a perl expression
exec quit Perl and execute a system command
exists test that a hash key exists
exit exit from the Perl script
glob expand a directory listing using shell wildcards
gmtime current time in GMT
grep filter an array for entries that meet a criterion
index find location of a substring inside a larger string
int throw away the fractional part of a floating point number
join join an array together into a string
keys return the keys of a hash
kill send a signal to one or more processes
last exit enclosing loop
lc convert string to lowercase
lcfirst lowercase first character of string
length find length of string
local temporarily replace the value of a global variable
localtime return time in local timezone
log natural logarithm
m// pattern match operation
map perform on operation on each member of array or list
mkdir make a new directory
my create a local variable
next jump to the top of enclosing loop
open open a file for reading or writing
opendir open a directory for listing
pack pack a list into a compact binary representation
package create a new namespace for a module
pop pop the last item off the end of an array
print print to terminal or a file
printf formatted print to a terminal or file
push push a value onto the end of an array
q/STRING/ generalized single-quote operation
qq/STRING/ generalized double-quote operation
qx/STRING/ generalized backtick operation
qw/STRING/ turn a space-delimited string of words into a list
rand random number generator
read read binary data from a file
readdir read the contents of a directory
readline read a line from a text file
readlink determine the target of a symbolic link
redo restart a loop from the top
ref return the type of a variable reference
rename rename or move a file
require load functions defined in a library file
return return a value from a user-defined subroutine
reverse reverse a string or list
rewinddir rewind a directory handle to the beginning
rindex find a substring in a larger string, from right to left
rmdir remove a directory
s/// pattern substitution operation
scalar force an expression to be treated as a scalar
seek reposition a filehandle to an arbitrary point in a file
select make a filehandle the default for output
shift shift a value off the beginning of an array
sin sine
sleep put the script to sleep for a while
sort sort an array or list by user-specified criteria
splice insert/delete array items
split split a string into pieces according to a pattern
sprintf formatted string creation
sqrt square root
stat get information about a file
sub define a subroutine
substr extract a substring from a string
symlink create a symbolic link
system execute an operating system command, then return to Perl
tell return the position of a filehandle within a file
tie associate a variable with a database
time return number of seconds since January 1, 1970
tr/// replace characters in a string
truncate truncate a file (make it smaller)
uc uppercase a string
ucfirst uppercase first character of a string
umask change file creation mask
undef undefine (remove) a variable
unlink delete a file
unpack the reverse of pack
untie the reverse of tie
unshift move a value onto the beginning of an array
use import variables and functions from a library module
values return the values of a hash variable
wantarray return true in an array context
warn print a warning to standard error
write formatted report generation

Creating Your Own Functions

You can define your own functions or redefine the built-in ones using the sub function. This is described in more detail in a later.

Learn perl easy part 2

No comments: