It has been occurred a lot of times that one has to test a code using data from a file. It can be anything like checking for a pattern in a file to taking some input. If you want to check the code without opening the file and reading it. One can use the __DATA__ marker provided by perl as a pseudo-datafile.
Steps to follow:
1) At the end of the code use __DATA__ marker and copy paste or write the contents of the file you wish to test exactly from the next line of _DATA_.
2) Use while (){ -- your code here -- }.
#!/usr/bin/perl
use strict;
use warnings;
while () {
chomp $_;
print "Found" if $_ =~ /(t\w+)/;
print $1;
}
__DATA__
hello there how r u
Output of the above program will be “there”.
Note: If you have any queries do leave your comments.
Showing posts with label perl tips. Show all posts
Showing posts with label perl tips. Show all posts
Tuesday, December 18, 2007
__DATA__ a Virtual File In Perl
Posted by
Nexis
at
9:24 PM
4
comments
Labels: perl tips
Thursday, November 22, 2007
Some Perl Tips
- No doubt the first tip is to use strict in whatever code you write. It helps in avoiding the typo and many other errors which otherwise are real difficult to bebug.
- When using if it is not necessary to emboss the condition in ()’s when if is used as the last part of the statement.
- @ARGV is the array which holds all the parameters passed to a perl program through a command line.
- For conditions in perl “”, 0 , “0”, undefined is false, everything else is true.
- It is confusing for some people to remember how unless works. One can remember it in a simple way by saying if not this then this happens. i.e unless (people){do this}; can be interpreted as if not people do this.
- When you want to comment a large amount of code you can always use a condition which will always be false. eg. if (1 > 2) { ...... }
If anyone of you have any other perl tips which you follow as a practice, please leave it in the comments section. I would like to add it to the list with your name as contributor and let people efficiently do their perl coding.
Posted by
Nexis
at
1:03 AM
0
comments
Labels: perl tips
Subscribe to:
Posts (Atom)