Perl Script - find line beginning with X?

Licursi

New member
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!
 
!/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;
 
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
 
Back
Top