Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old August 12th, 2008, 05:27 AM
Member
 
Join Date: Jul 2008
Posts: 41
Default 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
  2.  
  3. $data_file = "test.txt";
  4. open(EXPORTFILE, $data_file) || die("Could not open file!");
  5.  print "Opened $data_file\n";
  6.  
  7. $counter = 0;
  8. while(($line=<EXPORTFILE>) && ($counter<100)) {
  9.  
  10.         if($counter == 0) {
  11.         print "Skip $counter \n";
  12.         $counter++;
  13.         next;
  14.         }
  15.  
  16.         print "COUNTER: $counter \n";
  17.         chomp($line);
  18.         print "$line \n";
  19.         $counter++;
  20.  
  21. }
  22.  
  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.

Thanks.
Reply
  #2  
Old August 12th, 2008, 05:31 AM
eWish's Avatar
Moderator
 
Join Date: Jul 2007
Location: Arkansas
Posts: 837
Default

Have a look at the Tie:File module it will be able to achieve what you want.

--Kevin
Reply
  #3  
Old August 12th, 2008, 05:36 AM
nithinpes's Avatar
Expert
 
Join Date: Dec 2007
Age: 24
Posts: 366
Default

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. }
  7.  
  8.  

Last edited by nithinpes; August 12th, 2008 at 05:37 AM. Reason: edited text
Reply
  #4  
Old August 12th, 2008, 06:55 AM
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Posts: 3,662
Default

$. (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.
Reply
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles