Tuesday, November 6, 2012

Perl programming #2


Yesterday we learnt about installing perl in windows (Didn't read yesterday's post? check here Perl programming #1 )and how to “print” using perl!
Today, let’s start with the basics, how to get input using perl?

To get a text file from user using perl:
Just it is very simple, type as follows,


This will get the file name. This also works in perl,


No need to give STDIN! Just the open and closed angular brackets are itself considered as standard input.

Then, always give chomp after the standard input, this chomp is nothing but “chop” which chops the “enter” à new line character i.e., whenever you give an input, you press “enter” which will be considered as a new line character. In order to remove that new line character, chomp must be given.

How to use chomp? Use as follows,


Simple, this chops the new line character from your input.
Let us look at sample program for getting a text file and a word or pattern.
Program for getting a DNAFILE and printing the file content: (sample.pl)

print "enter a dna sequence file\n";

print "file not found\n";

print "DNA seq. is\n",$dna;

O/P of the program sample.pl

Here, DNAFILENAME is the file handler. Here, we used unless for checking, whether the given file name exists or not.

For opening the file, we can give just  as,


don’t forget the semicolon.

Don’t forget to give the line,


This assigns the content of the given dnafile to “$dnafile”
With out assigning this if you are just proceeding, you will get the output printed as the “file name” and not the file content.

“join” command is given for joining the spaces in the file. This helps when you are working with DNA and protein sequences.

$dna=~s/\s//g; This is also given for removing the spaces in the file

$dna=uc($dna); This changes the content of the file into upper case(UC)

“close” is used for closing the file,

print – It prints everything given within double quotes, even \n must be given within quotes, but, the variables like $dnafile must not be given within the quotes. Check the syntax given in the program.

Program for getting a pattern or word from the user and printing it (sample1.pl)

print "enter a pattern\n";
print "Pattern is\n",$pattern;

O/P of the program sample1.pl

Here, no file handlers are used. Once you try executing the programs, you could easily understand!

Try printing the output, after using “join” and the line “$dna=~s/\s//g” for knowing their difference. Here “g” stands for global i.e., removes the space globally.

Any doubts? Kindly comment. I’ll try to clear your doubts.

:) Happy perl-ing :)

No comments:

Post a Comment