Question:

Perl Script - find line beginning with X?

by  |  earlier

0 LIKES UnLike

Hi,

I need some simple logic for a function that is opening a file and looking for a line beginning with IDX. I already have the code to open the file I just need the search part.

In english something that says next if(not equal to IDX)

Thanks!

 Tags:

   Report

3 ANSWERS


  1. !/usr/bin/perl -w

    use strict;

    open( INFIL, "</foo.txt" ) or die $!;

    while( my $lin = <INFIL> ) {

      unless( $lin =~ m@^IDX@ ) { next; }

      // found it!

      last; // if you're only interested in the first one

    }

    close INFIL;


  2. You can transfer the contents of a file to an array like this:

    $FILE = "file.txt";

    open (FILE) or die "Can't open the file!";

    @fileinput = <FILE>;

    then you can use a loop like usual to step through the array and compare the current index to IDX.  

    Good luck.

  3. You want a regular expression (regex or regexp).  They can be very in depth, but they're easy once you get the hang of them.  You want something like this:

    if(open(FILE,"myfile.txt")) {

      while(<FILE>) {

        if(/^IDX/) {

          #Code here-- your line is in the $_ variable, complete with newline

        }

      }

    }

    Here, you're doing a test on the $_ variable to see if it matches the regexp /^IDX/.  You can perform that same check on other variables by using something like this:

    if($foo =~ /^IDX/) { ... }

    The carat is a special character meaning "beginning of line".  So if you wanted instead to search for any line that had "IDX" in it (not just at the front), you'd use /IDX/ instead.  There's a lot to learn about regexes, and they're frequently used in many languages-- many are even based on Perl's style.  So they're good to learn more about!

    DaveE

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions