print lines from a text file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lilly07
    New Member
    • Jul 2008
    • 89

    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:
    Code:
    #!usr/bin/perl
    
    $data_file = "test.txt";
    open(EXPORTFILE, $data_file) || die("Could not open file!");
     print "Opened $data_file\n";
    
    $counter = 0;
    while(($line=<EXPORTFILE>) && ($counter<100)) {
    
            if($counter == 0) {
            print "Skip $counter \n";
            $counter++;
            next;
            }
    
            print "COUNTER: $counter \n";
            chomp($line);
            print "$line \n";
            $counter++;
    
    }
    
    close EXPORTFILE;
    exit(0);
    Is it possible to skip $line or jump every 4 $line(ie) the lines in that file. Please let me know.

    Thanks.
  • eWish
    Recognized Expert Contributor
    • Jul 2007
    • 973

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

    --Kevin

    Comment

    • nithinpes
      Recognized Expert Contributor
      • Dec 2007
      • 410

      #3
      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.
      Code:
      my @lines = <EXPORTFILE>;
      ###print lines 2,6,10,14........
      for(my $i=1; $i<@lines;) {
        print "$lines[$i]";
        $i+ =4;
      }
      Last edited by nithinpes; Aug 12 '08, 04:37 AM. Reason: edited text

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        $. (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.

        Comment

        Working...