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.
Tuesday, December 18, 2007
__DATA__ a Virtual File In Perl
Subscribe to:
Post Comments (Atom)
4 comments:
Good bit of information for testing of things like regexs. Although, you may want to make a note that _DATA_ should not be used when using Mod Perl as Mod Perl tends to break when it is used.
Regards,
Jeff
Thanks for the valuable information JLK
Perhaps the while statement would be
while ( < DATA > ) {
with more recent versions of Perl
would be better if it is like this
while()
{
}
__DATA__
Post a Comment