By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,179 Members | 970 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,179 IT Pros & Developers. It's quick & easy.

print lines from a text file

P: 89
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
Share this Question
Share on Google+
3 Replies

Expert 100+
P: 971
Have a look at the Tie:File module it will be able to achieve what you want.

Aug 12 '08 #2

Expert 100+
P: 410
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 2.5K+
P: 4,059
$. (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.