467,081 Members | 1,275 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,081 developers. It's quick & easy.

print lines from a text file

I am new to perl. I would like to open a file and print 2,6,10,14.. etc lines of that file content. How to do it? I amm able to open a file and print the contetnts as below:
Expand|Select|Wrap|Line Numbers
  1. #!usr/bin/perl
  3. $data_file = "test.txt";
  4. open(EXPORTFILE, $data_file) || die("Could not open file!");
  5.  print "Opened $data_file\n";
  7. $counter = 0;
  8. while(($line=<EXPORTFILE>) && ($counter<100)) {
  10.         if($counter == 0) {
  11.         print "Skip $counter \n";
  12.         $counter++;
  13.         next;
  14.         }
  16.         print "COUNTER: $counter \n";
  17.         chomp($line);
  18.         print "$line \n";
  19.         $counter++;
  21. }
  23. close EXPORTFILE;
  24. exit(0);
Is it possible to skip $line or jump every 4 $line(ie) the lines in that file. Please let me know.

Aug 12 '08 #1
  • viewed: 2412
3 Replies
Expert 512MB
Have a look at the Tie:File module it will be able to achieve what you want.

Aug 12 '08 #2
Expert 256MB
Also, you can read the entire file into an array and later increment the index of the array to print only the desired lines. Each element in the array would be each line in the file.
Expand|Select|Wrap|Line Numbers
  1. my @lines = <EXPORTFILE>;
  2. ###print lines 2,6,10,14........
  3. for(my $i=1; $i<@lines;) {
  4.   print "$lines[$i]";
  5.   $i+ =4;
  6. }
Aug 12 '08 #3
Expert 2GB
$. (dollar-sign dot) is the input record line number variable (files start at one unlike arrays, that start at zero). You can use the variable to find specific lines in files, but Tie::File does make it easy to do the same thing. Just keep in mind, the first line of a file is 0 (zero) if you use Tie::File since you are accessing the file as if it were an array.
Aug 12 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by MouseHart | last post: by
7 posts views Thread by Leonel Gayard | last post: by
7 posts views Thread by Ron | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.