CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
Text processing from a text file


New User

Aug 9, 2011, 5:50 AM

Post #1 of 3 (526 views)
Text processing from a text file Can't Post


I'm a very beginner in perl, and I have a (hopefully) simple question:

I have a bunch of large text files, where I try to pick up pieces of information without having to go through them manually.

Example text file:

Line 1
Line 2
Line 3

I'm using:
$file = $ARGV[0];
open IN, $file;
while (<IN>) process the files

The information I want to catch is at Line 1, but how I know that is the information I want at Line 1 is at Line 3. So basicly how do I backtrack back to the Line 1 to catch the information I want?

With grep I know I can use grep -B 2, and reprocess the output to pick up the info I want, but I just dont know how to do it in perl.

Any help is greatly appreciated!


Aug 9, 2011, 6:44 AM

Post #2 of 3 (520 views)
Re: [Jipa] Text processing from a text file [In reply to] Can't Post

Well, record number (in this case, line number) of an input filehandle is held in
the variable "$."; and you probably know about the default variable "$_".
So, if it's always lines 1 and 3 that's relevant to you, then:

$file = $ARGV[0]; 
open IN, $file or die $!;

while (<IN>) {
my $line = $_ if $. == 1;
if ( $. == 3 and $_ =~ /this is the one/ ) {
print $line, "\n";

New User

Aug 9, 2011, 4:06 PM

Post #3 of 3 (514 views)
Re: [mino] Text processing from a text file [In reply to] Can't Post

Aaaah! Thanks a ton. Ill try this out as soon as I can!


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives